clang  19.0.0git
SemaChecking.cpp
Go to the documentation of this file.
1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements extra semantic analysis beyond what is enforced
10 // by the C type system.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/APValue.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/AttrIterator.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/ExprOpenMP.h"
29 #include "clang/AST/FormatString.h"
30 #include "clang/AST/IgnoreExpr.h"
31 #include "clang/AST/NSAPI.h"
34 #include "clang/AST/RecordLayout.h"
35 #include "clang/AST/Stmt.h"
36 #include "clang/AST/TemplateBase.h"
37 #include "clang/AST/Type.h"
38 #include "clang/AST/TypeLoc.h"
41 #include "clang/Basic/CharInfo.h"
42 #include "clang/Basic/Diagnostic.h"
44 #include "clang/Basic/LLVM.h"
51 #include "clang/Basic/Specifiers.h"
52 #include "clang/Basic/SyncScope.h"
55 #include "clang/Basic/TargetInfo.h"
56 #include "clang/Basic/TypeTraits.h"
57 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
59 #include "clang/Sema/Lookup.h"
60 #include "clang/Sema/Ownership.h"
61 #include "clang/Sema/Scope.h"
62 #include "clang/Sema/ScopeInfo.h"
63 #include "clang/Sema/Sema.h"
65 #include "clang/Sema/SemaSYCL.h"
66 #include "llvm/ADT/APFloat.h"
67 #include "llvm/ADT/APInt.h"
68 #include "llvm/ADT/APSInt.h"
69 #include "llvm/ADT/ArrayRef.h"
70 #include "llvm/ADT/DenseMap.h"
71 #include "llvm/ADT/FoldingSet.h"
72 #include "llvm/ADT/STLExtras.h"
73 #include "llvm/ADT/SmallBitVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallString.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/StringExtras.h"
78 #include "llvm/ADT/StringRef.h"
79 #include "llvm/ADT/StringSet.h"
80 #include "llvm/ADT/StringSwitch.h"
81 #include "llvm/Support/AtomicOrdering.h"
82 #include "llvm/Support/Casting.h"
83 #include "llvm/Support/Compiler.h"
84 #include "llvm/Support/ConvertUTF.h"
85 #include "llvm/Support/ErrorHandling.h"
86 #include "llvm/Support/Format.h"
87 #include "llvm/Support/Locale.h"
88 #include "llvm/Support/MathExtras.h"
89 #include "llvm/Support/SaveAndRestore.h"
90 #include "llvm/Support/raw_ostream.h"
91 #include "llvm/TargetParser/RISCVTargetParser.h"
92 #include "llvm/TargetParser/Triple.h"
93 #include <algorithm>
94 #include <bitset>
95 #include <cassert>
96 #include <cctype>
97 #include <cstddef>
98 #include <cstdint>
99 #include <functional>
100 #include <limits>
101 #include <optional>
102 #include <string>
103 #include <tuple>
104 #include <utility>
105 
106 using namespace clang;
107 using namespace sema;
108 
109 static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
110  const Expr *E);
111 
113  unsigned ByteNo) const {
114  return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
115  Context.getTargetInfo());
116 }
117 
118 static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A,
120  return (A << 8) | B;
121 }
122 
123 /// Checks that a call expression's argument count is at least the desired
124 /// number. This is useful when doing custom type-checking on a variadic
125 /// function. Returns true on error.
126 static bool checkArgCountAtLeast(Sema &S, CallExpr *Call,
127  unsigned MinArgCount) {
128  unsigned ArgCount = Call->getNumArgs();
129  if (ArgCount >= MinArgCount)
130  return false;
131 
132  return S.Diag(Call->getEndLoc(), diag::err_typecheck_call_too_few_args)
133  << 0 /*function call*/ << MinArgCount << ArgCount
134  << /*is non object*/ 0 << Call->getSourceRange();
135 }
136 
137 /// Checks that a call expression's argument count is at most the desired
138 /// number. This is useful when doing custom type-checking on a variadic
139 /// function. Returns true on error.
140 static bool checkArgCountAtMost(Sema &S, CallExpr *Call, unsigned MaxArgCount) {
141  unsigned ArgCount = Call->getNumArgs();
142  if (ArgCount <= MaxArgCount)
143  return false;
144  return S.Diag(Call->getEndLoc(),
145  diag::err_typecheck_call_too_many_args_at_most)
146  << 0 /*function call*/ << MaxArgCount << ArgCount
147  << /*is non object*/ 0 << Call->getSourceRange();
148 }
149 
150 /// Checks that a call expression's argument count is in the desired range. This
151 /// is useful when doing custom type-checking on a variadic function. Returns
152 /// true on error.
153 static bool checkArgCountRange(Sema &S, CallExpr *Call, unsigned MinArgCount,
154  unsigned MaxArgCount) {
155  return checkArgCountAtLeast(S, Call, MinArgCount) ||
156  checkArgCountAtMost(S, Call, MaxArgCount);
157 }
158 
159 /// Checks that a call expression's argument count is the desired number.
160 /// This is useful when doing custom type-checking. Returns true on error.
161 static bool checkArgCount(Sema &S, CallExpr *Call, unsigned DesiredArgCount) {
162  unsigned ArgCount = Call->getNumArgs();
163  if (ArgCount == DesiredArgCount)
164  return false;
165 
166  if (checkArgCountAtLeast(S, Call, DesiredArgCount))
167  return true;
168  assert(ArgCount > DesiredArgCount && "should have diagnosed this");
169 
170  // Highlight all the excess arguments.
171  SourceRange Range(Call->getArg(DesiredArgCount)->getBeginLoc(),
172  Call->getArg(ArgCount - 1)->getEndLoc());
173 
174  return S.Diag(Range.getBegin(), diag::err_typecheck_call_too_many_args)
175  << 0 /*function call*/ << DesiredArgCount << ArgCount
176  << /*is non object*/ 0 << Call->getArg(1)->getSourceRange();
177 }
178 
179 static bool convertArgumentToType(Sema &S, Expr *&Value, QualType Ty) {
180  if (Value->isTypeDependent())
181  return false;
182 
183  InitializedEntity Entity =
185  ExprResult Result =
187  if (Result.isInvalid())
188  return true;
189  Value = Result.get();
190  return false;
191 }
192 
193 /// Check that the first argument to __builtin_annotation is an integer
194 /// and the second argument is a non-wide string literal.
195 static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall) {
196  if (checkArgCount(S, TheCall, 2))
197  return true;
198 
199  // First argument should be an integer.
200  Expr *ValArg = TheCall->getArg(0);
201  QualType Ty = ValArg->getType();
202  if (!Ty->isIntegerType()) {
203  S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
204  << ValArg->getSourceRange();
205  return true;
206  }
207 
208  // Second argument should be a constant string.
209  Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
210  StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
211  if (!Literal || !Literal->isOrdinary()) {
212  S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
213  << StrArg->getSourceRange();
214  return true;
215  }
216 
217  TheCall->setType(Ty);
218  return false;
219 }
220 
221 static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
222  // We need at least one argument.
223  if (TheCall->getNumArgs() < 1) {
224  S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
225  << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
226  << TheCall->getCallee()->getSourceRange();
227  return true;
228  }
229 
230  // All arguments should be wide string literals.
231  for (Expr *Arg : TheCall->arguments()) {
232  auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
233  if (!Literal || !Literal->isWide()) {
234  S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
235  << Arg->getSourceRange();
236  return true;
237  }
238  }
239 
240  return false;
241 }
242 
243 /// Check that the argument to __builtin_addressof is a glvalue, and set the
244 /// result type to the corresponding pointer type.
245 static bool BuiltinAddressof(Sema &S, CallExpr *TheCall) {
246  if (checkArgCount(S, TheCall, 1))
247  return true;
248 
249  ExprResult Arg(TheCall->getArg(0));
250  QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
251  if (ResultType.isNull())
252  return true;
253 
254  TheCall->setArg(0, Arg.get());
255  TheCall->setType(ResultType);
256  return false;
257 }
258 
259 /// Check that the argument to __builtin_function_start is a function.
260 static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
261  if (checkArgCount(S, TheCall, 1))
262  return true;
263 
265  if (Arg.isInvalid())
266  return true;
267 
268  TheCall->setArg(0, Arg.get());
269  const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
271 
272  if (!FD) {
273  S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
274  << TheCall->getSourceRange();
275  return true;
276  }
277 
278  return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
279  TheCall->getBeginLoc());
280 }
281 
282 /// Check the number of arguments and set the result type to
283 /// the argument type.
284 static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
285  if (checkArgCount(S, TheCall, 1))
286  return true;
287 
288  TheCall->setType(TheCall->getArg(0)->getType());
289  return false;
290 }
291 
292 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
293 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
294 /// type (but not a function pointer) and that the alignment is a power-of-two.
295 static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
296  if (checkArgCount(S, TheCall, 2))
297  return true;
298 
299  clang::Expr *Source = TheCall->getArg(0);
300  bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
301 
302  auto IsValidIntegerType = [](QualType Ty) {
303  return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
304  };
305  QualType SrcTy = Source->getType();
306  // We should also be able to use it with arrays (but not functions!).
307  if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
308  SrcTy = S.Context.getDecayedType(SrcTy);
309  }
310  if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
311  SrcTy->isFunctionPointerType()) {
312  // FIXME: this is not quite the right error message since we don't allow
313  // floating point types, or member pointers.
314  S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
315  << SrcTy;
316  return true;
317  }
318 
319  clang::Expr *AlignOp = TheCall->getArg(1);
320  if (!IsValidIntegerType(AlignOp->getType())) {
321  S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
322  << AlignOp->getType();
323  return true;
324  }
325  Expr::EvalResult AlignResult;
326  unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
327  // We can't check validity of alignment if it is value dependent.
328  if (!AlignOp->isValueDependent() &&
329  AlignOp->EvaluateAsInt(AlignResult, S.Context,
331  llvm::APSInt AlignValue = AlignResult.Val.getInt();
332  llvm::APSInt MaxValue(
333  llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
334  if (AlignValue < 1) {
335  S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
336  return true;
337  }
338  if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
339  S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
340  << toString(MaxValue, 10);
341  return true;
342  }
343  if (!AlignValue.isPowerOf2()) {
344  S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
345  return true;
346  }
347  if (AlignValue == 1) {
348  S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
349  << IsBooleanAlignBuiltin;
350  }
351  }
352 
355  SourceLocation(), Source);
356  if (SrcArg.isInvalid())
357  return true;
358  TheCall->setArg(0, SrcArg.get());
359  ExprResult AlignArg =
361  S.Context, AlignOp->getType(), false),
362  SourceLocation(), AlignOp);
363  if (AlignArg.isInvalid())
364  return true;
365  TheCall->setArg(1, AlignArg.get());
366  // For align_up/align_down, the return type is the same as the (potentially
367  // decayed) argument type including qualifiers. For is_aligned(), the result
368  // is always bool.
369  TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
370  return false;
371 }
372 
373 static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) {
374  if (checkArgCount(S, TheCall, 3))
375  return true;
376 
377  std::pair<unsigned, const char *> Builtins[] = {
378  { Builtin::BI__builtin_add_overflow, "ckd_add" },
379  { Builtin::BI__builtin_sub_overflow, "ckd_sub" },
380  { Builtin::BI__builtin_mul_overflow, "ckd_mul" },
381  };
382 
383  bool CkdOperation = llvm::any_of(Builtins, [&](const std::pair<unsigned,
384  const char *> &P) {
385  return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
387  S.getSourceManager(), S.getLangOpts()) == P.second;
388  });
389 
390  auto ValidCkdIntType = [](QualType QT) {
391  // A valid checked integer type is an integer type other than a plain char,
392  // bool, a bit-precise type, or an enumeration type.
393  if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
394  return (BT->getKind() >= BuiltinType::Short &&
395  BT->getKind() <= BuiltinType::Int128) || (
396  BT->getKind() >= BuiltinType::UShort &&
397  BT->getKind() <= BuiltinType::UInt128) ||
398  BT->getKind() == BuiltinType::UChar ||
399  BT->getKind() == BuiltinType::SChar;
400  return false;
401  };
402 
403  // First two arguments should be integers.
404  for (unsigned I = 0; I < 2; ++I) {
406  if (Arg.isInvalid()) return true;
407  TheCall->setArg(I, Arg.get());
408 
409  QualType Ty = Arg.get()->getType();
410  bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
411  if (!IsValid) {
412  S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
413  << CkdOperation << Ty << Arg.get()->getSourceRange();
414  return true;
415  }
416  }
417 
418  // Third argument should be a pointer to a non-const integer.
419  // IRGen correctly handles volatile, restrict, and address spaces, and
420  // the other qualifiers aren't possible.
421  {
423  if (Arg.isInvalid()) return true;
424  TheCall->setArg(2, Arg.get());
425 
426  QualType Ty = Arg.get()->getType();
427  const auto *PtrTy = Ty->getAs<PointerType>();
428  if (!PtrTy ||
429  !PtrTy->getPointeeType()->isIntegerType() ||
430  (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
431  PtrTy->getPointeeType().isConstQualified()) {
432  S.Diag(Arg.get()->getBeginLoc(),
433  diag::err_overflow_builtin_must_be_ptr_int)
434  << CkdOperation << Ty << Arg.get()->getSourceRange();
435  return true;
436  }
437  }
438 
439  // Disallow signed bit-precise integer args larger than 128 bits to mul
440  // function until we improve backend support.
441  if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
442  for (unsigned I = 0; I < 3; ++I) {
443  const auto Arg = TheCall->getArg(I);
444  // Third argument will be a pointer.
445  auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
446  if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
447  S.getASTContext().getIntWidth(Ty) > 128)
448  return S.Diag(Arg->getBeginLoc(),
449  diag::err_overflow_builtin_bit_int_max_size)
450  << 128;
451  }
452  }
453 
454  return false;
455 }
456 
457 namespace {
458 struct BuiltinDumpStructGenerator {
459  Sema &S;
460  CallExpr *TheCall;
461  SourceLocation Loc = TheCall->getBeginLoc();
462  SmallVector<Expr *, 32> Actions;
463  DiagnosticErrorTrap ErrorTracker;
464  PrintingPolicy Policy;
465 
466  BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
467  : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
468  Policy(S.Context.getPrintingPolicy()) {
469  Policy.AnonymousTagLocations = false;
470  }
471 
472  Expr *makeOpaqueValueExpr(Expr *Inner) {
473  auto *OVE = new (S.Context)
474  OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
475  Inner->getObjectKind(), Inner);
476  Actions.push_back(OVE);
477  return OVE;
478  }
479 
480  Expr *getStringLiteral(llvm::StringRef Str) {
482  // Wrap the literal in parentheses to attach a source location.
483  return new (S.Context) ParenExpr(Loc, Loc, Lit);
484  }
485 
486  bool callPrintFunction(llvm::StringRef Format,
487  llvm::ArrayRef<Expr *> Exprs = {}) {
489  assert(TheCall->getNumArgs() >= 2);
490  Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
491  Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());
492  Args.push_back(getStringLiteral(Format));
493  Args.insert(Args.end(), Exprs.begin(), Exprs.end());
494 
495  // Register a note to explain why we're performing the call.
498  Ctx.PointOfInstantiation = Loc;
499  Ctx.CallArgs = Args.data();
500  Ctx.NumCallArgs = Args.size();
502 
503  ExprResult RealCall =
504  S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1),
505  TheCall->getBeginLoc(), Args, TheCall->getRParenLoc());
506 
508  if (!RealCall.isInvalid())
509  Actions.push_back(RealCall.get());
510  // Bail out if we've hit any errors, even if we managed to build the
511  // call. We don't want to produce more than one error.
512  return RealCall.isInvalid() || ErrorTracker.hasErrorOccurred();
513  }
514 
515  Expr *getIndentString(unsigned Depth) {
516  if (!Depth)
517  return nullptr;
518 
520  Indent.resize(Depth * Policy.Indentation, ' ');
521  return getStringLiteral(Indent);
522  }
523 
525  return getStringLiteral(T.getAsString(Policy));
526  }
527 
528  bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
529  llvm::raw_svector_ostream OS(Str);
530 
531  // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
532  // than trying to print a single character.
533  if (auto *BT = T->getAs<BuiltinType>()) {
534  switch (BT->getKind()) {
535  case BuiltinType::Bool:
536  OS << "%d";
537  return true;
538  case BuiltinType::Char_U:
539  case BuiltinType::UChar:
540  OS << "%hhu";
541  return true;
542  case BuiltinType::Char_S:
543  case BuiltinType::SChar:
544  OS << "%hhd";
545  return true;
546  default:
547  break;
548  }
549  }
550 
552  if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) {
553  // We were able to guess how to format this.
554  if (Specifier.getConversionSpecifier().getKind() ==
556  // Wrap double-quotes around a '%s' specifier and limit its maximum
557  // length. Ideally we'd also somehow escape special characters in the
558  // contents but printf doesn't support that.
559  // FIXME: '%s' formatting is not safe in general.
560  OS << '"';
561  Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
562  Specifier.toString(OS);
563  OS << '"';
564  // FIXME: It would be nice to include a '...' if the string doesn't fit
565  // in the length limit.
566  } else {
567  Specifier.toString(OS);
568  }
569  return true;
570  }
571 
572  if (T->isPointerType()) {
573  // Format all pointers with '%p'.
574  OS << "%p";
575  return true;
576  }
577 
578  return false;
579  }
580 
581  bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
582  Expr *IndentLit = getIndentString(Depth);
583  Expr *TypeLit = getTypeString(S.Context.getRecordType(RD));
584  if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit})
585  : callPrintFunction("%s", {TypeLit}))
586  return true;
587 
588  return dumpRecordValue(RD, E, IndentLit, Depth);
589  }
590 
591  // Dump a record value. E should be a pointer or lvalue referring to an RD.
592  bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
593  unsigned Depth) {
594  // FIXME: Decide what to do if RD is a union. At least we should probably
595  // turn off printing `const char*` members with `%s`, because that is very
596  // likely to crash if that's not the active member. Whatever we decide, we
597  // should document it.
598 
599  // Build an OpaqueValueExpr so we can refer to E more than once without
600  // triggering re-evaluation.
601  Expr *RecordArg = makeOpaqueValueExpr(E);
602  bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
603 
604  if (callPrintFunction(" {\n"))
605  return true;
606 
607  // Dump each base class, regardless of whether they're aggregates.
608  if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
609  for (const auto &Base : CXXRD->bases()) {
610  QualType BaseType =
611  RecordArgIsPtr ? S.Context.getPointerType(Base.getType())
612  : S.Context.getLValueReferenceType(Base.getType());
613  ExprResult BasePtr = S.BuildCStyleCastExpr(
614  Loc, S.Context.getTrivialTypeSourceInfo(BaseType, Loc), Loc,
615  RecordArg);
616  if (BasePtr.isInvalid() ||
617  dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(),
618  Depth + 1))
619  return true;
620  }
621  }
622 
623  Expr *FieldIndentArg = getIndentString(Depth + 1);
624 
625  // Dump each field.
626  for (auto *D : RD->decls()) {
627  auto *IFD = dyn_cast<IndirectFieldDecl>(D);
628  auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);
629  if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
630  continue;
631 
632  llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
633  llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
634  getTypeString(FD->getType()),
635  getStringLiteral(FD->getName())};
636 
637  if (FD->isBitField()) {
638  Format += ": %zu ";
640  llvm::APInt BitWidth(S.Context.getIntWidth(SizeT),
641  FD->getBitWidthValue(S.Context));
642  Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc));
643  }
644 
645  Format += "=";
646 
647  ExprResult Field =
649  CXXScopeSpec(), Loc, IFD,
650  DeclAccessPair::make(IFD, AS_public), RecordArg, Loc)
652  RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD,
654  DeclarationNameInfo(FD->getDeclName(), Loc));
655  if (Field.isInvalid())
656  return true;
657 
658  auto *InnerRD = FD->getType()->getAsRecordDecl();
659  auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD);
660  if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
661  // Recursively print the values of members of aggregate record type.
662  if (callPrintFunction(Format, Args) ||
663  dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1))
664  return true;
665  } else {
666  Format += " ";
667  if (appendFormatSpecifier(FD->getType(), Format)) {
668  // We know how to print this field.
669  Args.push_back(Field.get());
670  } else {
671  // We don't know how to print this field. Print out its address
672  // with a format specifier that a smart tool will be able to
673  // recognize and treat specially.
674  Format += "*%p";
675  ExprResult FieldAddr =
676  S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get());
677  if (FieldAddr.isInvalid())
678  return true;
679  Args.push_back(FieldAddr.get());
680  }
681  Format += "\n";
682  if (callPrintFunction(Format, Args))
683  return true;
684  }
685  }
686 
687  return RecordIndent ? callPrintFunction("%s}\n", RecordIndent)
688  : callPrintFunction("}\n");
689  }
690 
691  Expr *buildWrapper() {
692  auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions,
694  TheCall->setType(Wrapper->getType());
695  TheCall->setValueKind(Wrapper->getValueKind());
696  return Wrapper;
697  }
698 };
699 } // namespace
700 
702  if (checkArgCountAtLeast(S, TheCall, 2))
703  return ExprError();
704 
705  ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0));
706  if (PtrArgResult.isInvalid())
707  return ExprError();
708  TheCall->setArg(0, PtrArgResult.get());
709 
710  // First argument should be a pointer to a struct.
711  QualType PtrArgType = PtrArgResult.get()->getType();
712  if (!PtrArgType->isPointerType() ||
713  !PtrArgType->getPointeeType()->isRecordType()) {
714  S.Diag(PtrArgResult.get()->getBeginLoc(),
715  diag::err_expected_struct_pointer_argument)
716  << 1 << TheCall->getDirectCallee() << PtrArgType;
717  return ExprError();
718  }
719  QualType Pointee = PtrArgType->getPointeeType();
720  const RecordDecl *RD = Pointee->getAsRecordDecl();
721  // Try to instantiate the class template as appropriate; otherwise, access to
722  // its data() may lead to a crash.
723  if (S.RequireCompleteType(PtrArgResult.get()->getBeginLoc(), Pointee,
724  diag::err_incomplete_type))
725  return ExprError();
726  // Second argument is a callable, but we can't fully validate it until we try
727  // calling it.
728  QualType FnArgType = TheCall->getArg(1)->getType();
729  if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
730  !FnArgType->isBlockPointerType() &&
731  !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
732  auto *BT = FnArgType->getAs<BuiltinType>();
733  switch (BT ? BT->getKind() : BuiltinType::Void) {
734  case BuiltinType::Dependent:
735  case BuiltinType::Overload:
736  case BuiltinType::BoundMember:
737  case BuiltinType::PseudoObject:
738  case BuiltinType::UnknownAny:
739  case BuiltinType::BuiltinFn:
740  // This might be a callable.
741  break;
742 
743  default:
744  S.Diag(TheCall->getArg(1)->getBeginLoc(),
745  diag::err_expected_callable_argument)
746  << 2 << TheCall->getDirectCallee() << FnArgType;
747  return ExprError();
748  }
749  }
750 
751  BuiltinDumpStructGenerator Generator(S, TheCall);
752 
753  // Wrap parentheses around the given pointer. This is not necessary for
754  // correct code generation, but it means that when we pretty-print the call
755  // arguments in our diagnostics we will produce '(&s)->n' instead of the
756  // incorrect '&s->n'.
757  Expr *PtrArg = PtrArgResult.get();
758  PtrArg = new (S.Context)
759  ParenExpr(PtrArg->getBeginLoc(),
760  S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg);
761  if (Generator.dumpUnnamedRecord(RD, PtrArg, 0))
762  return ExprError();
763 
764  return Generator.buildWrapper();
765 }
766 
767 static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
768  if (checkArgCount(S, BuiltinCall, 2))
769  return true;
770 
771  SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
772  Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
773  Expr *Call = BuiltinCall->getArg(0);
774  Expr *Chain = BuiltinCall->getArg(1);
775 
776  if (Call->getStmtClass() != Stmt::CallExprClass) {
777  S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
778  << Call->getSourceRange();
779  return true;
780  }
781 
782  auto CE = cast<CallExpr>(Call);
783  if (CE->getCallee()->getType()->isBlockPointerType()) {
784  S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
785  << Call->getSourceRange();
786  return true;
787  }
788 
789  const Decl *TargetDecl = CE->getCalleeDecl();
790  if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
791  if (FD->getBuiltinID()) {
792  S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
793  << Call->getSourceRange();
794  return true;
795  }
796 
797  if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
798  S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
799  << Call->getSourceRange();
800  return true;
801  }
802 
803  ExprResult ChainResult = S.UsualUnaryConversions(Chain);
804  if (ChainResult.isInvalid())
805  return true;
806  if (!ChainResult.get()->getType()->isPointerType()) {
807  S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
808  << Chain->getSourceRange();
809  return true;
810  }
811 
812  QualType ReturnTy = CE->getCallReturnType(S.Context);
813  QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
814  QualType BuiltinTy = S.Context.getFunctionType(
815  ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
816  QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
817 
818  Builtin =
819  S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
820 
821  BuiltinCall->setType(CE->getType());
822  BuiltinCall->setValueKind(CE->getValueKind());
823  BuiltinCall->setObjectKind(CE->getObjectKind());
824  BuiltinCall->setCallee(Builtin);
825  BuiltinCall->setArg(1, ChainResult.get());
826 
827  return false;
828 }
829 
830 namespace {
831 
832 class ScanfDiagnosticFormatHandler
834  // Accepts the argument index (relative to the first destination index) of the
835  // argument whose size we want.
836  using ComputeSizeFunction =
837  llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
838 
839  // Accepts the argument index (relative to the first destination index), the
840  // destination size, and the source size).
841  using DiagnoseFunction =
842  llvm::function_ref<void(unsigned, unsigned, unsigned)>;
843 
844  ComputeSizeFunction ComputeSizeArgument;
845  DiagnoseFunction Diagnose;
846 
847 public:
848  ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
849  DiagnoseFunction Diagnose)
850  : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
851 
852  bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
853  const char *StartSpecifier,
854  unsigned specifierLen) override {
855  if (!FS.consumesDataArgument())
856  return true;
857 
858  unsigned NulByte = 0;
859  switch ((FS.getConversionSpecifier().getKind())) {
860  default:
861  return true;
864  NulByte = 1;
865  break;
867  break;
868  }
869 
870  analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
871  if (FW.getHowSpecified() !=
872  analyze_format_string::OptionalAmount::HowSpecified::Constant)
873  return true;
874 
875  unsigned SourceSize = FW.getConstantAmount() + NulByte;
876 
877  std::optional<llvm::APSInt> DestSizeAPS =
878  ComputeSizeArgument(FS.getArgIndex());
879  if (!DestSizeAPS)
880  return true;
881 
882  unsigned DestSize = DestSizeAPS->getZExtValue();
883 
884  if (DestSize < SourceSize)
885  Diagnose(FS.getArgIndex(), DestSize, SourceSize);
886 
887  return true;
888  }
889 };
890 
891 class EstimateSizeFormatHandler
893  size_t Size;
894  /// Whether the format string contains Linux kernel's format specifier
895  /// extension.
896  bool IsKernelCompatible = true;
897 
898 public:
899  EstimateSizeFormatHandler(StringRef Format)
900  : Size(std::min(Format.find(0), Format.size()) +
901  1 /* null byte always written by sprintf */) {}
902 
903  bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
904  const char *, unsigned SpecifierLen,
905  const TargetInfo &) override {
906 
907  const size_t FieldWidth = computeFieldWidth(FS);
908  const size_t Precision = computePrecision(FS);
909 
910  // The actual format.
911  switch (FS.getConversionSpecifier().getKind()) {
912  // Just a char.
915  Size += std::max(FieldWidth, (size_t)1);
916  break;
917  // Just an integer.
927  Size += std::max(FieldWidth, Precision);
928  break;
929 
930  // %g style conversion switches between %f or %e style dynamically.
931  // %g removes trailing zeros, and does not print decimal point if there are
932  // no digits that follow it. Thus %g can print a single digit.
933  // FIXME: If it is alternative form:
934  // For g and G conversions, trailing zeros are not removed from the result.
937  Size += 1;
938  break;
939 
940  // Floating point number in the form '[+]ddd.ddd'.
943  Size += std::max(FieldWidth, 1 /* integer part */ +
944  (Precision ? 1 + Precision
945  : 0) /* period + decimal */);
946  break;
947 
948  // Floating point number in the form '[-]d.ddde[+-]dd'.
951  Size +=
952  std::max(FieldWidth,
953  1 /* integer part */ +
954  (Precision ? 1 + Precision : 0) /* period + decimal */ +
955  1 /* e or E letter */ + 2 /* exponent */);
956  break;
957 
958  // Floating point number in the form '[-]0xh.hhhhp±dd'.
961  Size +=
962  std::max(FieldWidth,
963  2 /* 0x */ + 1 /* integer part */ +
964  (Precision ? 1 + Precision : 0) /* period + decimal */ +
965  1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
966  break;
967 
968  // Just a string.
971  Size += FieldWidth;
972  break;
973 
974  // Just a pointer in the form '0xddd'.
976  // Linux kernel has its own extesion for `%p` specifier.
977  // Kernel Document:
978  // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
979  IsKernelCompatible = false;
980  Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
981  break;
982 
983  // A plain percent.
985  Size += 1;
986  break;
987 
988  default:
989  break;
990  }
991 
992  Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
993 
994  if (FS.hasAlternativeForm()) {
995  switch (FS.getConversionSpecifier().getKind()) {
996  // For o conversion, it increases the precision, if and only if necessary,
997  // to force the first digit of the result to be a zero
998  // (if the value and precision are both 0, a single 0 is printed)
1000  // For b conversion, a nonzero result has 0b prefixed to it.
1002  // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
1003  // it.
1006  // Note: even when the prefix is added, if
1007  // (prefix_width <= FieldWidth - formatted_length) holds,
1008  // the prefix does not increase the format
1009  // size. e.g.(("%#3x", 0xf) is "0xf")
1010 
1011  // If the result is zero, o, b, x, X adds nothing.
1012  break;
1013  // For a, A, e, E, f, F, g, and G conversions,
1014  // the result of converting a floating-point number always contains a
1015  // decimal-point
1024  Size += (Precision ? 0 : 1);
1025  break;
1026  // For other conversions, the behavior is undefined.
1027  default:
1028  break;
1029  }
1030  }
1031  assert(SpecifierLen <= Size && "no underflow");
1032  Size -= SpecifierLen;
1033  return true;
1034  }
1035 
1036  size_t getSizeLowerBound() const { return Size; }
1037  bool isKernelCompatible() const { return IsKernelCompatible; }
1038 
1039 private:
1040  static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1041  const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1042  size_t FieldWidth = 0;
1044  FieldWidth = FW.getConstantAmount();
1045  return FieldWidth;
1046  }
1047 
1048  static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1049  const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1050  size_t Precision = 0;
1051 
1052  // See man 3 printf for default precision value based on the specifier.
1053  switch (FW.getHowSpecified()) {
1055  switch (FS.getConversionSpecifier().getKind()) {
1056  default:
1057  break;
1061  Precision = 1;
1062  break;
1069  Precision = 1;
1070  break;
1077  Precision = 6;
1078  break;
1080  Precision = 1;
1081  break;
1082  }
1083  break;
1085  Precision = FW.getConstantAmount();
1086  break;
1087  default:
1088  break;
1089  }
1090  return Precision;
1091  }
1092 };
1093 
1094 } // namespace
1095 
1096 static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1097  StringRef &FormatStrRef, size_t &StrLen,
1098  ASTContext &Context) {
1099  if (const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
1100  Format && (Format->isOrdinary() || Format->isUTF8())) {
1101  FormatStrRef = Format->getString();
1102  const ConstantArrayType *T =
1103  Context.getAsConstantArrayType(Format->getType());
1104  assert(T && "String literal not of constant array type!");
1105  size_t TypeSize = T->getZExtSize();
1106  // In case there's a null byte somewhere.
1107  StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
1108  return true;
1109  }
1110  return false;
1111 }
1112 
1113 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1114  CallExpr *TheCall) {
1115  if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
1116  isConstantEvaluatedContext())
1117  return;
1118 
1119  bool UseDABAttr = false;
1120  const FunctionDecl *UseDecl = FD;
1121 
1122  const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
1123  if (DABAttr) {
1124  UseDecl = DABAttr->getFunction();
1125  assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1126  UseDABAttr = true;
1127  }
1128 
1129  unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
1130 
1131  if (!BuiltinID)
1132  return;
1133 
1134  const TargetInfo &TI = getASTContext().getTargetInfo();
1135  unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
1136 
1137  auto TranslateIndex = [&](unsigned Index) -> std::optional<unsigned> {
1138  // If we refer to a diagnose_as_builtin attribute, we need to change the
1139  // argument index to refer to the arguments of the called function. Unless
1140  // the index is out of bounds, which presumably means it's a variadic
1141  // function.
1142  if (!UseDABAttr)
1143  return Index;
1144  unsigned DABIndices = DABAttr->argIndices_size();
1145  unsigned NewIndex = Index < DABIndices
1146  ? DABAttr->argIndices_begin()[Index]
1147  : Index - DABIndices + FD->getNumParams();
1148  if (NewIndex >= TheCall->getNumArgs())
1149  return std::nullopt;
1150  return NewIndex;
1151  };
1152 
1153  auto ComputeExplicitObjectSizeArgument =
1154  [&](unsigned Index) -> std::optional<llvm::APSInt> {
1155  std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1156  if (!IndexOptional)
1157  return std::nullopt;
1158  unsigned NewIndex = *IndexOptional;
1159  Expr::EvalResult Result;
1160  Expr *SizeArg = TheCall->getArg(NewIndex);
1161  if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
1162  return std::nullopt;
1163  llvm::APSInt Integer = Result.Val.getInt();
1164  Integer.setIsUnsigned(true);
1165  return Integer;
1166  };
1167 
1168  auto ComputeSizeArgument =
1169  [&](unsigned Index) -> std::optional<llvm::APSInt> {
1170  // If the parameter has a pass_object_size attribute, then we should use its
1171  // (potentially) more strict checking mode. Otherwise, conservatively assume
1172  // type 0.
1173  int BOSType = 0;
1174  // This check can fail for variadic functions.
1175  if (Index < FD->getNumParams()) {
1176  if (const auto *POS =
1177  FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
1178  BOSType = POS->getType();
1179  }
1180 
1181  std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1182  if (!IndexOptional)
1183  return std::nullopt;
1184  unsigned NewIndex = *IndexOptional;
1185 
1186  if (NewIndex >= TheCall->getNumArgs())
1187  return std::nullopt;
1188 
1189  const Expr *ObjArg = TheCall->getArg(NewIndex);
1190  uint64_t Result;
1191  if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
1192  return std::nullopt;
1193 
1194  // Get the object size in the target's size_t width.
1195  return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
1196  };
1197 
1198  auto ComputeStrLenArgument =
1199  [&](unsigned Index) -> std::optional<llvm::APSInt> {
1200  std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1201  if (!IndexOptional)
1202  return std::nullopt;
1203  unsigned NewIndex = *IndexOptional;
1204 
1205  const Expr *ObjArg = TheCall->getArg(NewIndex);
1206  uint64_t Result;
1207  if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
1208  return std::nullopt;
1209  // Add 1 for null byte.
1210  return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
1211  };
1212 
1213  std::optional<llvm::APSInt> SourceSize;
1214  std::optional<llvm::APSInt> DestinationSize;
1215  unsigned DiagID = 0;
1216  bool IsChkVariant = false;
1217 
1218  auto GetFunctionName = [&]() {
1219  StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
1220  // Skim off the details of whichever builtin was called to produce a better
1221  // diagnostic, as it's unlikely that the user wrote the __builtin
1222  // explicitly.
1223  if (IsChkVariant) {
1224  FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
1225  FunctionName = FunctionName.drop_back(std::strlen("_chk"));
1226  } else {
1227  FunctionName.consume_front("__builtin_");
1228  }
1229  return FunctionName;
1230  };
1231 
1232  switch (BuiltinID) {
1233  default:
1234  return;
1235  case Builtin::BI__builtin_strcpy:
1236  case Builtin::BIstrcpy: {
1237  DiagID = diag::warn_fortify_strlen_overflow;
1238  SourceSize = ComputeStrLenArgument(1);
1239  DestinationSize = ComputeSizeArgument(0);
1240  break;
1241  }
1242 
1243  case Builtin::BI__builtin___strcpy_chk: {
1244  DiagID = diag::warn_fortify_strlen_overflow;
1245  SourceSize = ComputeStrLenArgument(1);
1246  DestinationSize = ComputeExplicitObjectSizeArgument(2);
1247  IsChkVariant = true;
1248  break;
1249  }
1250 
1251  case Builtin::BIscanf:
1252  case Builtin::BIfscanf:
1253  case Builtin::BIsscanf: {
1254  unsigned FormatIndex = 1;
1255  unsigned DataIndex = 2;
1256  if (BuiltinID == Builtin::BIscanf) {
1257  FormatIndex = 0;
1258  DataIndex = 1;
1259  }
1260 
1261  const auto *FormatExpr =
1262  TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1263 
1264  StringRef FormatStrRef;
1265  size_t StrLen;
1266  if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1267  return;
1268 
1269  auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1270  unsigned SourceSize) {
1271  DiagID = diag::warn_fortify_scanf_overflow;
1272  unsigned Index = ArgIndex + DataIndex;
1273  StringRef FunctionName = GetFunctionName();
1274  DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
1275  PDiag(DiagID) << FunctionName << (Index + 1)
1276  << DestSize << SourceSize);
1277  };
1278 
1279  auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1280  return ComputeSizeArgument(Index + DataIndex);
1281  };
1282  ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1283  const char *FormatBytes = FormatStrRef.data();
1285  FormatBytes + StrLen, getLangOpts(),
1286  Context.getTargetInfo());
1287 
1288  // Unlike the other cases, in this one we have already issued the diagnostic
1289  // here, so no need to continue (because unlike the other cases, here the
1290  // diagnostic refers to the argument number).
1291  return;
1292  }
1293 
1294  case Builtin::BIsprintf:
1295  case Builtin::BI__builtin___sprintf_chk: {
1296  size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
1297  auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1298 
1299  StringRef FormatStrRef;
1300  size_t StrLen;
1301  if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1302  EstimateSizeFormatHandler H(FormatStrRef);
1303  const char *FormatBytes = FormatStrRef.data();
1305  H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1306  Context.getTargetInfo(), false)) {
1307  DiagID = H.isKernelCompatible()
1308  ? diag::warn_format_overflow
1309  : diag::warn_format_overflow_non_kprintf;
1310  SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1311  .extOrTrunc(SizeTypeWidth);
1312  if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
1313  DestinationSize = ComputeExplicitObjectSizeArgument(2);
1314  IsChkVariant = true;
1315  } else {
1316  DestinationSize = ComputeSizeArgument(0);
1317  }
1318  break;
1319  }
1320  }
1321  return;
1322  }
1323  case Builtin::BI__builtin___memcpy_chk:
1324  case Builtin::BI__builtin___memmove_chk:
1325  case Builtin::BI__builtin___memset_chk:
1326  case Builtin::BI__builtin___strlcat_chk:
1327  case Builtin::BI__builtin___strlcpy_chk:
1328  case Builtin::BI__builtin___strncat_chk:
1329  case Builtin::BI__builtin___strncpy_chk:
1330  case Builtin::BI__builtin___stpncpy_chk:
1331  case Builtin::BI__builtin___memccpy_chk:
1332  case Builtin::BI__builtin___mempcpy_chk: {
1333  DiagID = diag::warn_builtin_chk_overflow;
1334  SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1335  DestinationSize =
1336  ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1337  IsChkVariant = true;
1338  break;
1339  }
1340 
1341  case Builtin::BI__builtin___snprintf_chk:
1342  case Builtin::BI__builtin___vsnprintf_chk: {
1343  DiagID = diag::warn_builtin_chk_overflow;
1344  SourceSize = ComputeExplicitObjectSizeArgument(1);
1345  DestinationSize = ComputeExplicitObjectSizeArgument(3);
1346  IsChkVariant = true;
1347  break;
1348  }
1349 
1350  case Builtin::BIstrncat:
1351  case Builtin::BI__builtin_strncat:
1352  case Builtin::BIstrncpy:
1353  case Builtin::BI__builtin_strncpy:
1354  case Builtin::BIstpncpy:
1355  case Builtin::BI__builtin_stpncpy: {
1356  // Whether these functions overflow depends on the runtime strlen of the
1357  // string, not just the buffer size, so emitting the "always overflow"
1358  // diagnostic isn't quite right. We should still diagnose passing a buffer
1359  // size larger than the destination buffer though; this is a runtime abort
1360  // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1361  DiagID = diag::warn_fortify_source_size_mismatch;
1362  SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1363  DestinationSize = ComputeSizeArgument(0);
1364  break;
1365  }
1366 
1367  case Builtin::BImemcpy:
1368  case Builtin::BI__builtin_memcpy:
1369  case Builtin::BImemmove:
1370  case Builtin::BI__builtin_memmove:
1371  case Builtin::BImemset:
1372  case Builtin::BI__builtin_memset:
1373  case Builtin::BImempcpy:
1374  case Builtin::BI__builtin_mempcpy: {
1375  DiagID = diag::warn_fortify_source_overflow;
1376  SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1377  DestinationSize = ComputeSizeArgument(0);
1378  break;
1379  }
1380  case Builtin::BIsnprintf:
1381  case Builtin::BI__builtin_snprintf:
1382  case Builtin::BIvsnprintf:
1383  case Builtin::BI__builtin_vsnprintf: {
1384  DiagID = diag::warn_fortify_source_size_mismatch;
1385  SourceSize = ComputeExplicitObjectSizeArgument(1);
1386  const auto *FormatExpr = TheCall->getArg(2)->IgnoreParenImpCasts();
1387  StringRef FormatStrRef;
1388  size_t StrLen;
1389  if (SourceSize &&
1390  ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1391  EstimateSizeFormatHandler H(FormatStrRef);
1392  const char *FormatBytes = FormatStrRef.data();
1394  H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1395  Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1396  llvm::APSInt FormatSize =
1397  llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1398  .extOrTrunc(SizeTypeWidth);
1399  if (FormatSize > *SourceSize && *SourceSize != 0) {
1400  unsigned TruncationDiagID =
1401  H.isKernelCompatible() ? diag::warn_format_truncation
1402  : diag::warn_format_truncation_non_kprintf;
1403  SmallString<16> SpecifiedSizeStr;
1404  SmallString<16> FormatSizeStr;
1405  SourceSize->toString(SpecifiedSizeStr, /*Radix=*/10);
1406  FormatSize.toString(FormatSizeStr, /*Radix=*/10);
1407  DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1408  PDiag(TruncationDiagID)
1409  << GetFunctionName() << SpecifiedSizeStr
1410  << FormatSizeStr);
1411  }
1412  }
1413  }
1414  DestinationSize = ComputeSizeArgument(0);
1415  }
1416  }
1417 
1418  if (!SourceSize || !DestinationSize ||
1419  llvm::APSInt::compareValues(*SourceSize, *DestinationSize) <= 0)
1420  return;
1421 
1422  StringRef FunctionName = GetFunctionName();
1423 
1424  SmallString<16> DestinationStr;
1425  SmallString<16> SourceStr;
1426  DestinationSize->toString(DestinationStr, /*Radix=*/10);
1427  SourceSize->toString(SourceStr, /*Radix=*/10);
1428  DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1429  PDiag(DiagID)
1430  << FunctionName << DestinationStr << SourceStr);
1431 }
1432 
1433 static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1434  Scope::ScopeFlags NeededScopeFlags,
1435  unsigned DiagID) {
1436  // Scopes aren't available during instantiation. Fortunately, builtin
1437  // functions cannot be template args so they cannot be formed through template
1438  // instantiation. Therefore checking once during the parse is sufficient.
1439  if (SemaRef.inTemplateInstantiation())
1440  return false;
1441 
1442  Scope *S = SemaRef.getCurScope();
1443  while (S && !S->isSEHExceptScope())
1444  S = S->getParent();
1445  if (!S || !(S->getFlags() & NeededScopeFlags)) {
1446  auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1447  SemaRef.Diag(TheCall->getExprLoc(), DiagID)
1448  << DRE->getDecl()->getIdentifier();
1449  return true;
1450  }
1451 
1452  return false;
1453 }
1454 
1455 static inline bool isBlockPointer(Expr *Arg) {
1456  return Arg->getType()->isBlockPointerType();
1457 }
1458 
1459 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
1460 /// void*, which is a requirement of device side enqueue.
1461 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
1462  const BlockPointerType *BPT =
1463  cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1464  ArrayRef<QualType> Params =
1465  BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
1466  unsigned ArgCounter = 0;
1467  bool IllegalParams = false;
1468  // Iterate through the block parameters until either one is found that is not
1469  // a local void*, or the block is valid.
1470  for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
1471  I != E; ++I, ++ArgCounter) {
1472  if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
1473  (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
1475  // Get the location of the error. If a block literal has been passed
1476  // (BlockExpr) then we can point straight to the offending argument,
1477  // else we just point to the variable reference.
1478  SourceLocation ErrorLoc;
1479  if (isa<BlockExpr>(BlockArg)) {
1480  BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
1481  ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
1482  } else if (isa<DeclRefExpr>(BlockArg)) {
1483  ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
1484  }
1485  S.Diag(ErrorLoc,
1486  diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
1487  IllegalParams = true;
1488  }
1489  }
1490 
1491  return IllegalParams;
1492 }
1493 
1494 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
1495  // OpenCL device can support extension but not the feature as extension
1496  // requires subgroup independent forward progress, but subgroup independent
1497  // forward progress is optional in OpenCL C 3.0 __opencl_c_subgroups feature.
1498  if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts()) &&
1499  !S.getOpenCLOptions().isSupported("__opencl_c_subgroups",
1500  S.getLangOpts())) {
1501  S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
1502  << 1 << Call->getDirectCallee()
1503  << "cl_khr_subgroups or __opencl_c_subgroups";
1504  return true;
1505  }
1506  return false;
1507 }
1508 
1509 static bool OpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
1510  if (checkArgCount(S, TheCall, 2))
1511  return true;
1512 
1513  if (checkOpenCLSubgroupExt(S, TheCall))
1514  return true;
1515 
1516  // First argument is an ndrange_t type.
1517  Expr *NDRangeArg = TheCall->getArg(0);
1518  if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1519  S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1520  << TheCall->getDirectCallee() << "'ndrange_t'";
1521  return true;
1522  }
1523 
1524  Expr *BlockArg = TheCall->getArg(1);
1525  if (!isBlockPointer(BlockArg)) {
1526  S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1527  << TheCall->getDirectCallee() << "block";
1528  return true;
1529  }
1530  return checkOpenCLBlockArgs(S, BlockArg);
1531 }
1532 
1533 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
1534 /// get_kernel_work_group_size
1535 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
1537  if (checkArgCount(S, TheCall, 1))
1538  return true;
1539 
1540  Expr *BlockArg = TheCall->getArg(0);
1541  if (!isBlockPointer(BlockArg)) {
1542  S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1543  << TheCall->getDirectCallee() << "block";
1544  return true;
1545  }
1546  return checkOpenCLBlockArgs(S, BlockArg);
1547 }
1548 
1549 /// Diagnose integer type and any valid implicit conversion to it.
1550 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
1551  const QualType &IntType);
1552 
1554  unsigned Start, unsigned End) {
1555  bool IllegalParams = false;
1556  for (unsigned I = Start; I <= End; ++I)
1557  IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
1558  S.Context.getSizeType());
1559  return IllegalParams;
1560 }
1561 
1562 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
1563 /// 'local void*' parameter of passed block.
1565  Expr *BlockArg,
1566  unsigned NumNonVarArgs) {
1567  const BlockPointerType *BPT =
1568  cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1569  unsigned NumBlockParams =
1570  BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
1571  unsigned TotalNumArgs = TheCall->getNumArgs();
1572 
1573  // For each argument passed to the block, a corresponding uint needs to
1574  // be passed to describe the size of the local memory.
1575  if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
1576  S.Diag(TheCall->getBeginLoc(),
1577  diag::err_opencl_enqueue_kernel_local_size_args);
1578  return true;
1579  }
1580 
1581  // Check that the sizes of the local memory are specified by integers.
1582  return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
1583  TotalNumArgs - 1);
1584 }
1585 
1586 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
1587 /// overload formats specified in Table 6.13.17.1.
1588 /// int enqueue_kernel(queue_t queue,
1589 /// kernel_enqueue_flags_t flags,
1590 /// const ndrange_t ndrange,
1591 /// void (^block)(void))
1592 /// int enqueue_kernel(queue_t queue,
1593 /// kernel_enqueue_flags_t flags,
1594 /// const ndrange_t ndrange,
1595 /// uint num_events_in_wait_list,
1596 /// clk_event_t *event_wait_list,
1597 /// clk_event_t *event_ret,
1598 /// void (^block)(void))
1599 /// int enqueue_kernel(queue_t queue,
1600 /// kernel_enqueue_flags_t flags,
1601 /// const ndrange_t ndrange,
1602 /// void (^block)(local void*, ...),
1603 /// uint size0, ...)
1604 /// int enqueue_kernel(queue_t queue,
1605 /// kernel_enqueue_flags_t flags,
1606 /// const ndrange_t ndrange,
1607 /// uint num_events_in_wait_list,
1608 /// clk_event_t *event_wait_list,
1609 /// clk_event_t *event_ret,
1610 /// void (^block)(local void*, ...),
1611 /// uint size0, ...)
1612 static bool OpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
1613  unsigned NumArgs = TheCall->getNumArgs();
1614 
1615  if (NumArgs < 4) {
1616  S.Diag(TheCall->getBeginLoc(),
1617  diag::err_typecheck_call_too_few_args_at_least)
1618  << 0 << 4 << NumArgs << /*is non object*/ 0;
1619  return true;
1620  }
1621 
1622  Expr *Arg0 = TheCall->getArg(0);
1623  Expr *Arg1 = TheCall->getArg(1);
1624  Expr *Arg2 = TheCall->getArg(2);
1625  Expr *Arg3 = TheCall->getArg(3);
1626 
1627  // First argument always needs to be a queue_t type.
1628  if (!Arg0->getType()->isQueueT()) {
1629  S.Diag(TheCall->getArg(0)->getBeginLoc(),
1630  diag::err_opencl_builtin_expected_type)
1631  << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
1632  return true;
1633  }
1634 
1635  // Second argument always needs to be a kernel_enqueue_flags_t enum value.
1636  if (!Arg1->getType()->isIntegerType()) {
1637  S.Diag(TheCall->getArg(1)->getBeginLoc(),
1638  diag::err_opencl_builtin_expected_type)
1639  << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
1640  return true;
1641  }
1642 
1643  // Third argument is always an ndrange_t type.
1644  if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1645  S.Diag(TheCall->getArg(2)->getBeginLoc(),
1646  diag::err_opencl_builtin_expected_type)
1647  << TheCall->getDirectCallee() << "'ndrange_t'";
1648  return true;
1649  }
1650 
1651  // With four arguments, there is only one form that the function could be
1652  // called in: no events and no variable arguments.
1653  if (NumArgs == 4) {
1654  // check that the last argument is the right block type.
1655  if (!isBlockPointer(Arg3)) {
1656  S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1657  << TheCall->getDirectCallee() << "block";
1658  return true;
1659  }
1660  // we have a block type, check the prototype
1661  const BlockPointerType *BPT =
1662  cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1663  if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1664  S.Diag(Arg3->getBeginLoc(),
1665  diag::err_opencl_enqueue_kernel_blocks_no_args);
1666  return true;
1667  }
1668  return false;
1669  }
1670  // we can have block + varargs.
1671  if (isBlockPointer(Arg3))
1672  return (checkOpenCLBlockArgs(S, Arg3) ||
1673  checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1674  // last two cases with either exactly 7 args or 7 args and varargs.
1675  if (NumArgs >= 7) {
1676  // check common block argument.
1677  Expr *Arg6 = TheCall->getArg(6);
1678  if (!isBlockPointer(Arg6)) {
1679  S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1680  << TheCall->getDirectCallee() << "block";
1681  return true;
1682  }
1683  if (checkOpenCLBlockArgs(S, Arg6))
1684  return true;
1685 
1686  // Forth argument has to be any integer type.
1687  if (!Arg3->getType()->isIntegerType()) {
1688  S.Diag(TheCall->getArg(3)->getBeginLoc(),
1689  diag::err_opencl_builtin_expected_type)
1690  << TheCall->getDirectCallee() << "integer";
1691  return true;
1692  }
1693  // check remaining common arguments.
1694  Expr *Arg4 = TheCall->getArg(4);
1695  Expr *Arg5 = TheCall->getArg(5);
1696 
1697  // Fifth argument is always passed as a pointer to clk_event_t.
1698  if (!Arg4->isNullPointerConstant(S.Context,
1701  S.Diag(TheCall->getArg(4)->getBeginLoc(),
1702  diag::err_opencl_builtin_expected_type)
1703  << TheCall->getDirectCallee()
1705  return true;
1706  }
1707 
1708  // Sixth argument is always passed as a pointer to clk_event_t.
1709  if (!Arg5->isNullPointerConstant(S.Context,
1711  !(Arg5->getType()->isPointerType() &&
1712  Arg5->getType()->getPointeeType()->isClkEventT())) {
1713  S.Diag(TheCall->getArg(5)->getBeginLoc(),
1714  diag::err_opencl_builtin_expected_type)
1715  << TheCall->getDirectCallee()
1717  return true;
1718  }
1719 
1720  if (NumArgs == 7)
1721  return false;
1722 
1723  return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1724  }
1725 
1726  // None of the specific case has been detected, give generic error
1727  S.Diag(TheCall->getBeginLoc(),
1728  diag::err_opencl_enqueue_kernel_incorrect_args);
1729  return true;
1730 }
1731 
1732 /// Returns OpenCL access qual.
1733 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1734  return D->getAttr<OpenCLAccessAttr>();
1735 }
1736 
1737 /// Returns true if pipe element type is different from the pointer.
1738 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1739  const Expr *Arg0 = Call->getArg(0);
1740  // First argument type should always be pipe.
1741  if (!Arg0->getType()->isPipeType()) {
1742  S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1743  << Call->getDirectCallee() << Arg0->getSourceRange();
1744  return true;
1745  }
1746  OpenCLAccessAttr *AccessQual =
1747  getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1748  // Validates the access qualifier is compatible with the call.
1749  // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1750  // read_only and write_only, and assumed to be read_only if no qualifier is
1751  // specified.
1752  switch (Call->getDirectCallee()->getBuiltinID()) {
1753  case Builtin::BIread_pipe:
1754  case Builtin::BIreserve_read_pipe:
1755  case Builtin::BIcommit_read_pipe:
1756  case Builtin::BIwork_group_reserve_read_pipe:
1757  case Builtin::BIsub_group_reserve_read_pipe:
1758  case Builtin::BIwork_group_commit_read_pipe:
1759  case Builtin::BIsub_group_commit_read_pipe:
1760  if (!(!AccessQual || AccessQual->isReadOnly())) {
1761  S.Diag(Arg0->getBeginLoc(),
1762  diag::err_opencl_builtin_pipe_invalid_access_modifier)
1763  << "read_only" << Arg0->getSourceRange();
1764  return true;
1765  }
1766  break;
1767  case Builtin::BIwrite_pipe:
1768  case Builtin::BIreserve_write_pipe:
1769  case Builtin::BIcommit_write_pipe:
1770  case Builtin::BIwork_group_reserve_write_pipe:
1771  case Builtin::BIsub_group_reserve_write_pipe:
1772  case Builtin::BIwork_group_commit_write_pipe:
1773  case Builtin::BIsub_group_commit_write_pipe:
1774  if (!(AccessQual && AccessQual->isWriteOnly())) {
1775  S.Diag(Arg0->getBeginLoc(),
1776  diag::err_opencl_builtin_pipe_invalid_access_modifier)
1777  << "write_only" << Arg0->getSourceRange();
1778  return true;
1779  }
1780  break;
1781  default:
1782  break;
1783  }
1784  return false;
1785 }
1786 
1787 /// Returns true if pipe element type is different from the pointer.
1788 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1789  const Expr *Arg0 = Call->getArg(0);
1790  const Expr *ArgIdx = Call->getArg(Idx);
1791  const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1792  const QualType EltTy = PipeTy->getElementType();
1793  const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1794  // The Idx argument should be a pointer and the type of the pointer and
1795  // the type of pipe element should also be the same.
1796  if (!ArgTy ||
1797  !S.Context.hasSameType(
1798  EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1799  S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1800  << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1801  << ArgIdx->getType() << ArgIdx->getSourceRange();
1802  return true;
1803  }
1804  return false;
1805 }
1806 
1807 // Performs semantic analysis for the read/write_pipe call.
1808 // \param S Reference to the semantic analyzer.
1809 // \param Call A pointer to the builtin call.
1810 // \return True if a semantic error has been found, false otherwise.
1811 static bool BuiltinRWPipe(Sema &S, CallExpr *Call) {
1812  // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1813  // functions have two forms.
1814  switch (Call->getNumArgs()) {
1815  case 2:
1816  if (checkOpenCLPipeArg(S, Call))
1817  return true;
1818  // The call with 2 arguments should be
1819  // read/write_pipe(pipe T, T*).
1820  // Check packet type T.
1821  if (checkOpenCLPipePacketType(S, Call, 1))
1822  return true;
1823  break;
1824 
1825  case 4: {
1826  if (checkOpenCLPipeArg(S, Call))
1827  return true;
1828  // The call with 4 arguments should be
1829  // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1830  // Check reserve_id_t.
1831  if (!Call->getArg(1)->getType()->isReserveIDT()) {
1832  S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1833  << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1834  << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1835  return true;
1836  }
1837 
1838  // Check the index.
1839  const Expr *Arg2 = Call->getArg(2);
1840  if (!Arg2->getType()->isIntegerType() &&
1841  !Arg2->getType()->isUnsignedIntegerType()) {
1842  S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1843  << Call->getDirectCallee() << S.Context.UnsignedIntTy
1844  << Arg2->getType() << Arg2->getSourceRange();
1845  return true;
1846  }
1847 
1848  // Check packet type T.
1849  if (checkOpenCLPipePacketType(S, Call, 3))
1850  return true;
1851  } break;
1852  default:
1853  S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1854  << Call->getDirectCallee() << Call->getSourceRange();
1855  return true;
1856  }
1857 
1858  return false;
1859 }
1860 
1861 // Performs a semantic analysis on the {work_group_/sub_group_
1862 // /_}reserve_{read/write}_pipe
1863 // \param S Reference to the semantic analyzer.
1864 // \param Call The call to the builtin function to be analyzed.
1865 // \return True if a semantic error was found, false otherwise.
1866 static bool BuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1867  if (checkArgCount(S, Call, 2))
1868  return true;
1869 
1870  if (checkOpenCLPipeArg(S, Call))
1871  return true;
1872 
1873  // Check the reserve size.
1874  if (!Call->getArg(1)->getType()->isIntegerType() &&
1875  !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1876  S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1877  << Call->getDirectCallee() << S.Context.UnsignedIntTy
1878  << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1879  return true;
1880  }
1881 
1882  // Since return type of reserve_read/write_pipe built-in function is
1883  // reserve_id_t, which is not defined in the builtin def file , we used int
1884  // as return type and need to override the return type of these functions.
1885  Call->setType(S.Context.OCLReserveIDTy);
1886 
1887  return false;
1888 }
1889 
1890 // Performs a semantic analysis on {work_group_/sub_group_
1891 // /_}commit_{read/write}_pipe
1892 // \param S Reference to the semantic analyzer.
1893 // \param Call The call to the builtin function to be analyzed.
1894 // \return True if a semantic error was found, false otherwise.
1895 static bool BuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1896  if (checkArgCount(S, Call, 2))
1897  return true;
1898 
1899  if (checkOpenCLPipeArg(S, Call))
1900  return true;
1901 
1902  // Check reserve_id_t.
1903  if (!Call->getArg(1)->getType()->isReserveIDT()) {
1904  S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1905  << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1906  << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1907  return true;
1908  }
1909 
1910  return false;
1911 }
1912 
1913 // Performs a semantic analysis on the call to built-in Pipe
1914 // Query Functions.
1915 // \param S Reference to the semantic analyzer.
1916 // \param Call The call to the builtin function to be analyzed.
1917 // \return True if a semantic error was found, false otherwise.
1918 static bool BuiltinPipePackets(Sema &S, CallExpr *Call) {
1919  if (checkArgCount(S, Call, 1))
1920  return true;
1921 
1922  if (!Call->getArg(0)->getType()->isPipeType()) {
1923  S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1924  << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1925  return true;
1926  }
1927 
1928  return false;
1929 }
1930 
1931 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1932 // Performs semantic analysis for the to_global/local/private call.
1933 // \param S Reference to the semantic analyzer.
1934 // \param BuiltinID ID of the builtin function.
1935 // \param Call A pointer to the builtin call.
1936 // \return True if a semantic error has been found, false otherwise.
1937 static bool OpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, CallExpr *Call) {
1938  if (checkArgCount(S, Call, 1))
1939  return true;
1940 
1941  auto RT = Call->getArg(0)->getType();
1942  if (!RT->isPointerType() || RT->getPointeeType()
1943  .getAddressSpace() == LangAS::opencl_constant) {
1944  S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1945  << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1946  return true;
1947  }
1948 
1949  if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1950  S.Diag(Call->getArg(0)->getBeginLoc(),
1951  diag::warn_opencl_generic_address_space_arg)
1952  << Call->getDirectCallee()->getNameInfo().getAsString()
1953  << Call->getArg(0)->getSourceRange();
1954  }
1955 
1956  RT = RT->getPointeeType();
1957  auto Qual = RT.getQualifiers();
1958  switch (BuiltinID) {
1959  case Builtin::BIto_global:
1960  Qual.setAddressSpace(LangAS::opencl_global);
1961  break;
1962  case Builtin::BIto_local:
1963  Qual.setAddressSpace(LangAS::opencl_local);
1964  break;
1965  case Builtin::BIto_private:
1966  Qual.setAddressSpace(LangAS::opencl_private);
1967  break;
1968  default:
1969  llvm_unreachable("Invalid builtin function");
1970  }
1971  Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1972  RT.getUnqualifiedType(), Qual)));
1973 
1974  return false;
1975 }
1976 
1977 namespace {
1978 enum PointerAuthOpKind {
1979  PAO_Strip,
1980  PAO_Sign,
1981  PAO_Auth,
1982  PAO_SignGeneric,
1983  PAO_Discriminator,
1984  PAO_BlendPointer,
1985  PAO_BlendInteger
1986 };
1987 }
1988 
1989 static bool checkPointerAuthEnabled(Sema &S, Expr *E) {
1990  if (S.getLangOpts().PointerAuthIntrinsics)
1991  return false;
1992 
1993  S.Diag(E->getExprLoc(), diag::err_ptrauth_disabled) << E->getSourceRange();
1994  return true;
1995 }
1996 
1997 static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1998  // Convert it to type 'int'.
1999  if (convertArgumentToType(S, Arg, S.Context.IntTy))
2000  return true;
2001 
2002  // Value-dependent expressions are okay; wait for template instantiation.
2003  if (Arg->isValueDependent())
2004  return false;
2005 
2006  unsigned KeyValue;
2007  return S.checkConstantPointerAuthKey(Arg, KeyValue);
2008 }
2009 
2010 bool Sema::checkConstantPointerAuthKey(Expr *Arg, unsigned &Result) {
2011  // Attempt to constant-evaluate the expression.
2012  std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Context);
2013  if (!KeyValue) {
2014  Diag(Arg->getExprLoc(), diag::err_expr_not_ice)
2015  << 0 << Arg->getSourceRange();
2016  return true;
2017  }
2018 
2019  // Ask the target to validate the key parameter.
2020  if (!Context.getTargetInfo().validatePointerAuthKey(*KeyValue)) {
2022  {
2023  llvm::raw_svector_ostream Str(Value);
2024  Str << *KeyValue;
2025  }
2026 
2027  Diag(Arg->getExprLoc(), diag::err_ptrauth_invalid_key)
2028  << Value << Arg->getSourceRange();
2029  return true;
2030  }
2031 
2032  Result = KeyValue->getZExtValue();
2033  return false;
2034 }
2035 
2036 static bool checkPointerAuthValue(Sema &S, Expr *&Arg,
2037  PointerAuthOpKind OpKind) {
2038  if (Arg->hasPlaceholderType()) {
2039  ExprResult R = S.CheckPlaceholderExpr(Arg);
2040  if (R.isInvalid())
2041  return true;
2042  Arg = R.get();
2043  }
2044 
2045  auto AllowsPointer = [](PointerAuthOpKind OpKind) {
2046  return OpKind != PAO_BlendInteger;
2047  };
2048  auto AllowsInteger = [](PointerAuthOpKind OpKind) {
2049  return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
2050  OpKind == PAO_SignGeneric;
2051  };
2052 
2053  // Require the value to have the right range of type.
2054  QualType ExpectedTy;
2055  if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
2056  ExpectedTy = Arg->getType().getUnqualifiedType();
2057  } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
2058  ExpectedTy = S.Context.VoidPtrTy;
2059  } else if (AllowsInteger(OpKind) &&
2061  ExpectedTy = S.Context.getUIntPtrType();
2062 
2063  } else {
2064  // Diagnose the failures.
2065  S.Diag(Arg->getExprLoc(), diag::err_ptrauth_value_bad_type)
2066  << unsigned(OpKind == PAO_Discriminator ? 1
2067  : OpKind == PAO_BlendPointer ? 2
2068  : OpKind == PAO_BlendInteger ? 3
2069  : 0)
2070  << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
2071  << Arg->getType() << Arg->getSourceRange();
2072  return true;
2073  }
2074 
2075  // Convert to that type. This should just be an lvalue-to-rvalue
2076  // conversion.
2077  if (convertArgumentToType(S, Arg, ExpectedTy))
2078  return true;
2079 
2080  // Warn about null pointers for non-generic sign and auth operations.
2081  if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
2083  S.Diag(Arg->getExprLoc(), OpKind == PAO_Sign
2084  ? diag::warn_ptrauth_sign_null_pointer
2085  : diag::warn_ptrauth_auth_null_pointer)
2086  << Arg->getSourceRange();
2087  }
2088 
2089  return false;
2090 }
2091 
2093  if (checkArgCount(S, Call, 2))
2094  return ExprError();
2095  if (checkPointerAuthEnabled(S, Call))
2096  return ExprError();
2097  if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Strip) ||
2098  checkPointerAuthKey(S, Call->getArgs()[1]))
2099  return ExprError();
2100 
2101  Call->setType(Call->getArgs()[0]->getType());
2102  return Call;
2103 }
2104 
2106  if (checkArgCount(S, Call, 2))
2107  return ExprError();
2108  if (checkPointerAuthEnabled(S, Call))
2109  return ExprError();
2110  if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_BlendPointer) ||
2111  checkPointerAuthValue(S, Call->getArgs()[1], PAO_BlendInteger))
2112  return ExprError();
2113 
2114  Call->setType(S.Context.getUIntPtrType());
2115  return Call;
2116 }
2117 
2119  if (checkArgCount(S, Call, 2))
2120  return ExprError();
2121  if (checkPointerAuthEnabled(S, Call))
2122  return ExprError();
2123  if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_SignGeneric) ||
2124  checkPointerAuthValue(S, Call->getArgs()[1], PAO_Discriminator))
2125  return ExprError();
2126 
2127  Call->setType(S.Context.getUIntPtrType());
2128  return Call;
2129 }
2130 
2132  PointerAuthOpKind OpKind) {
2133  if (checkArgCount(S, Call, 3))
2134  return ExprError();
2135  if (checkPointerAuthEnabled(S, Call))
2136  return ExprError();
2137  if (checkPointerAuthValue(S, Call->getArgs()[0], OpKind) ||
2138  checkPointerAuthKey(S, Call->getArgs()[1]) ||
2139  checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator))
2140  return ExprError();
2141 
2142  Call->setType(Call->getArgs()[0]->getType());
2143  return Call;
2144 }
2145 
2147  if (checkArgCount(S, Call, 5))
2148  return ExprError();
2149  if (checkPointerAuthEnabled(S, Call))
2150  return ExprError();
2151  if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
2152  checkPointerAuthKey(S, Call->getArgs()[1]) ||
2153  checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
2154  checkPointerAuthKey(S, Call->getArgs()[3]) ||
2155  checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator))
2156  return ExprError();
2157 
2158  Call->setType(Call->getArgs()[0]->getType());
2159  return Call;
2160 }
2161 
2162 static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall) {
2163  if (checkArgCount(S, TheCall, 1))
2164  return ExprError();
2165 
2166  // Compute __builtin_launder's parameter type from the argument.
2167  // The parameter type is:
2168  // * The type of the argument if it's not an array or function type,
2169  // Otherwise,
2170  // * The decayed argument type.
2171  QualType ParamTy = [&]() {
2172  QualType ArgTy = TheCall->getArg(0)->getType();
2173  if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
2174  return S.Context.getPointerType(Ty->getElementType());
2175  if (ArgTy->isFunctionType()) {
2176  return S.Context.getPointerType(ArgTy);
2177  }
2178  return ArgTy;
2179  }();
2180 
2181  TheCall->setType(ParamTy);
2182 
2183  auto DiagSelect = [&]() -> std::optional<unsigned> {
2184  if (!ParamTy->isPointerType())
2185  return 0;
2186  if (ParamTy->isFunctionPointerType())
2187  return 1;
2188  if (ParamTy->isVoidPointerType())
2189  return 2;
2190  return std::optional<unsigned>{};
2191  }();
2192  if (DiagSelect) {
2193  S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
2194  << *DiagSelect << TheCall->getSourceRange();
2195  return ExprError();
2196  }
2197 
2198  // We either have an incomplete class type, or we have a class template
2199  // whose instantiation has not been forced. Example:
2200  //
2201  // template <class T> struct Foo { T value; };
2202  // Foo<int> *p = nullptr;
2203  // auto *d = __builtin_launder(p);
2204  if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
2205  diag::err_incomplete_type))
2206  return ExprError();
2207 
2208  assert(ParamTy->getPointeeType()->isObjectType() &&
2209  "Unhandled non-object pointer case");
2210 
2211  InitializedEntity Entity =
2213  ExprResult Arg =
2214  S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
2215  if (Arg.isInvalid())
2216  return ExprError();
2217  TheCall->setArg(0, Arg.get());
2218 
2219  return TheCall;
2220 }
2221 
2222 // Emit an error and return true if the current object format type is in the
2223 // list of unsupported types.
2225  Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2226  ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2227  llvm::Triple::ObjectFormatType CurObjFormat =
2228  S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2229  if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
2230  S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2231  << TheCall->getSourceRange();
2232  return true;
2233  }
2234  return false;
2235 }
2236 
2237 // Emit an error and return true if the current architecture is not in the list
2238 // of supported architectures.
2239 static bool
2240 CheckBuiltinTargetInSupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2241  ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2242  llvm::Triple::ArchType CurArch =
2243  S.getASTContext().getTargetInfo().getTriple().getArch();
2244  if (llvm::is_contained(SupportedArchs, CurArch))
2245  return false;
2246  S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2247  << TheCall->getSourceRange();
2248  return true;
2249 }
2250 
2251 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2252  SourceLocation CallSiteLoc);
2253 
2254 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2255  CallExpr *TheCall) {
2256  switch (TI.getTriple().getArch()) {
2257  default:
2258  // Some builtins don't require additional checking, so just consider these
2259  // acceptable.
2260  return false;
2261  case llvm::Triple::arm:
2262  case llvm::Triple::armeb:
2263  case llvm::Triple::thumb:
2264  case llvm::Triple::thumbeb:
2265  return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2266  case llvm::Triple::aarch64:
2267  case llvm::Triple::aarch64_32:
2268  case llvm::Triple::aarch64_be:
2269  return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2270  case llvm::Triple::bpfeb:
2271  case llvm::Triple::bpfel:
2272  return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2273  case llvm::Triple::hexagon:
2274  return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2275  case llvm::Triple::mips:
2276  case llvm::Triple::mipsel:
2277  case llvm::Triple::mips64:
2278  case llvm::Triple::mips64el:
2279  return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2280  case llvm::Triple::systemz:
2281  return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2282  case llvm::Triple::x86:
2283  case llvm::Triple::x86_64:
2284  return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
2285  case llvm::Triple::ppc:
2286  case llvm::Triple::ppcle:
2287  case llvm::Triple::ppc64:
2288  case llvm::Triple::ppc64le:
2289  return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2290  case llvm::Triple::amdgcn:
2291  return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
2292  case llvm::Triple::riscv32:
2293  case llvm::Triple::riscv64:
2294  return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2295  case llvm::Triple::loongarch32:
2296  case llvm::Triple::loongarch64:
2297  return CheckLoongArchBuiltinFunctionCall(TI, BuiltinID, TheCall);
2298  case llvm::Triple::wasm32:
2299  case llvm::Triple::wasm64:
2300  return CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2301  case llvm::Triple::nvptx:
2302  case llvm::Triple::nvptx64:
2303  return CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2304  }
2305 }
2306 
2307 // Check if \p Ty is a valid type for the elementwise math builtins. If it is
2308 // not a valid type, emit an error message and return true. Otherwise return
2309 // false.
2311  QualType ArgTy, int ArgIndex) {
2312  if (!ArgTy->getAs<VectorType>() &&
2314  return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2315  << ArgIndex << /* vector, integer or float ty*/ 0 << ArgTy;
2316  }
2317 
2318  return false;
2319 }
2320 
2322  QualType ArgTy, int ArgIndex) {
2323  QualType EltTy = ArgTy;
2324  if (auto *VecTy = EltTy->getAs<VectorType>())
2325  EltTy = VecTy->getElementType();
2326 
2327  if (!EltTy->isRealFloatingType()) {
2328  return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2329  << ArgIndex << /* vector or float ty*/ 5 << ArgTy;
2330  }
2331 
2332  return false;
2333 }
2334 
2335 /// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2336 /// This checks that the target supports the builtin and that the string
2337 /// argument is constant and valid.
2338 static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2339  const TargetInfo *AuxTI, unsigned BuiltinID) {
2340  assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2341  BuiltinID == Builtin::BI__builtin_cpu_is) &&
2342  "Expecting __builtin_cpu_...");
2343 
2344  bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2345  const TargetInfo *TheTI = &TI;
2346  auto SupportsBI = [=](const TargetInfo *TInfo) {
2347  return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2348  (!IsCPUSupports && TInfo->supportsCpuIs()));
2349  };
2350  if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2351  TheTI = AuxTI;
2352 
2353  if (IsCPUSupports && !TheTI->supportsCpuSupports())
2354  return S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2355  << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2356  if (!IsCPUSupports && !TheTI->supportsCpuIs())
2357  return S.Diag(TheCall->getBeginLoc(),
2358  TI.getTriple().isOSAIX()
2359  ? diag::err_builtin_aix_os_unsupported
2360  : diag::err_builtin_target_unsupported)
2361  << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2362 
2363  Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts();
2364  // Check if the argument is a string literal.
2365  if (!isa<StringLiteral>(Arg))
2366  return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2367  << Arg->getSourceRange();
2368 
2369  // Check the contents of the string.
2370  StringRef Feature = cast<StringLiteral>(Arg)->getString();
2371  if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {
2372  S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)
2373  << Arg->getSourceRange();
2374  return false;
2375  }
2376  if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))
2377  return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2378  << Arg->getSourceRange();
2379  return false;
2380 }
2381 
2382 /// Checks that __builtin_popcountg was called with a single argument, which is
2383 /// an unsigned integer.
2384 static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2385  if (checkArgCount(S, TheCall, 1))
2386  return true;
2387 
2388  ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2389  if (ArgRes.isInvalid())
2390  return true;
2391 
2392  Expr *Arg = ArgRes.get();
2393  TheCall->setArg(0, Arg);
2394 
2395  QualType ArgTy = Arg->getType();
2396 
2397  if (!ArgTy->isUnsignedIntegerType()) {
2398  S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2399  << 1 << /*unsigned integer ty*/ 7 << ArgTy;
2400  return true;
2401  }
2402  return false;
2403 }
2404 
2405 /// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2406 /// an unsigned integer, and an optional second argument, which is promoted to
2407 /// an 'int'.
2408 static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2409  if (checkArgCountRange(S, TheCall, 1, 2))
2410  return true;
2411 
2412  ExprResult Arg0Res = S.DefaultLvalueConversion(TheCall->getArg(0));
2413  if (Arg0Res.isInvalid())
2414  return true;
2415 
2416  Expr *Arg0 = Arg0Res.get();
2417  TheCall->setArg(0, Arg0);
2418 
2419  QualType Arg0Ty = Arg0->getType();
2420 
2421  if (!Arg0Ty->isUnsignedIntegerType()) {
2422  S.Diag(Arg0->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2423  << 1 << /*unsigned integer ty*/ 7 << Arg0Ty;
2424  return true;
2425  }
2426 
2427  if (TheCall->getNumArgs() > 1) {
2428  ExprResult Arg1Res = S.UsualUnaryConversions(TheCall->getArg(1));
2429  if (Arg1Res.isInvalid())
2430  return true;
2431 
2432  Expr *Arg1 = Arg1Res.get();
2433  TheCall->setArg(1, Arg1);
2434 
2435  QualType Arg1Ty = Arg1->getType();
2436 
2437  if (!Arg1Ty->isSpecificBuiltinType(BuiltinType::Int)) {
2438  S.Diag(Arg1->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2439  << 2 << /*'int' ty*/ 8 << Arg1Ty;
2440  return true;
2441  }
2442  }
2443 
2444  return false;
2445 }
2446 
2447 ExprResult
2448 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2449  CallExpr *TheCall) {
2450  ExprResult TheCallResult(TheCall);
2451 
2452  // Find out if any arguments are required to be integer constant expressions.
2453  unsigned ICEArguments = 0;
2455  Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
2456  if (Error != ASTContext::GE_None)
2457  ICEArguments = 0; // Don't diagnose previously diagnosed errors.
2458 
2459  // If any arguments are required to be ICE's, check and diagnose.
2460  for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
2461  // Skip arguments not required to be ICE's.
2462  if ((ICEArguments & (1 << ArgNo)) == 0) continue;
2463 
2464  llvm::APSInt Result;
2465  // If we don't have enough arguments, continue so we can issue better
2466  // diagnostic in checkArgCount(...)
2467  if (ArgNo < TheCall->getNumArgs() &&
2468  BuiltinConstantArg(TheCall, ArgNo, Result))
2469  return true;
2470  ICEArguments &= ~(1 << ArgNo);
2471  }
2472 
2473  FPOptions FPO;
2474  switch (BuiltinID) {
2475  case Builtin::BI__builtin_cpu_supports:
2476  case Builtin::BI__builtin_cpu_is:
2477  if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall,
2478  Context.getAuxTargetInfo(), BuiltinID))
2479  return ExprError();
2480  break;
2481  case Builtin::BI__builtin_cpu_init:
2482  if (!Context.getTargetInfo().supportsCpuInit()) {
2483  Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2484  << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2485  return ExprError();
2486  }
2487  break;
2488  case Builtin::BI__builtin___CFStringMakeConstantString:
2489  // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
2490  // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
2492  *this, BuiltinID, TheCall,
2493  {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
2494  return ExprError();
2495  assert(TheCall->getNumArgs() == 1 &&
2496  "Wrong # arguments to builtin CFStringMakeConstantString");
2497  if (CheckObjCString(TheCall->getArg(0)))
2498  return ExprError();
2499  break;
2500  case Builtin::BI__builtin_ms_va_start:
2501  case Builtin::BI__builtin_stdarg_start:
2502  case Builtin::BI__builtin_va_start:
2503  if (BuiltinVAStart(BuiltinID, TheCall))
2504  return ExprError();
2505  break;
2506  case Builtin::BI__va_start: {
2507  switch (Context.getTargetInfo().getTriple().getArch()) {
2508  case llvm::Triple::aarch64:
2509  case llvm::Triple::arm:
2510  case llvm::Triple::thumb:
2511  if (BuiltinVAStartARMMicrosoft(TheCall))
2512  return ExprError();
2513  break;
2514  default:
2515  if (BuiltinVAStart(BuiltinID, TheCall))
2516  return ExprError();
2517  break;
2518  }
2519  break;
2520  }
2521 
2522  // The acquire, release, and no fence variants are ARM and AArch64 only.
2523  case Builtin::BI_interlockedbittestandset_acq:
2524  case Builtin::BI_interlockedbittestandset_rel:
2525  case Builtin::BI_interlockedbittestandset_nf:
2526  case Builtin::BI_interlockedbittestandreset_acq:
2527  case Builtin::BI_interlockedbittestandreset_rel:
2528  case Builtin::BI_interlockedbittestandreset_nf:
2530  *this, BuiltinID, TheCall,
2531  {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
2532  return ExprError();
2533  break;
2534 
2535  // The 64-bit bittest variants are x64, ARM, and AArch64 only.
2536  case Builtin::BI_bittest64:
2537  case Builtin::BI_bittestandcomplement64:
2538  case Builtin::BI_bittestandreset64:
2539  case Builtin::BI_bittestandset64:
2540  case Builtin::BI_interlockedbittestandreset64:
2541  case Builtin::BI_interlockedbittestandset64:
2542  if (CheckBuiltinTargetInSupported(*this, BuiltinID, TheCall,
2543  {llvm::Triple::x86_64, llvm::Triple::arm,
2544  llvm::Triple::thumb,
2545  llvm::Triple::aarch64}))
2546  return ExprError();
2547  break;
2548 
2549  case Builtin::BI__builtin_set_flt_rounds:
2550  if (CheckBuiltinTargetInSupported(*this, BuiltinID, TheCall,
2551  {llvm::Triple::x86, llvm::Triple::x86_64,
2552  llvm::Triple::arm, llvm::Triple::thumb,
2553  llvm::Triple::aarch64}))
2554  return ExprError();
2555  break;
2556 
2557  case Builtin::BI__builtin_isgreater:
2558  case Builtin::BI__builtin_isgreaterequal:
2559  case Builtin::BI__builtin_isless:
2560  case Builtin::BI__builtin_islessequal:
2561  case Builtin::BI__builtin_islessgreater:
2562  case Builtin::BI__builtin_isunordered:
2563  if (BuiltinUnorderedCompare(TheCall, BuiltinID))
2564  return ExprError();
2565  break;
2566  case Builtin::BI__builtin_fpclassify:
2567  if (BuiltinFPClassification(TheCall, 6, BuiltinID))
2568  return ExprError();
2569  break;
2570  case Builtin::BI__builtin_isfpclass:
2571  if (BuiltinFPClassification(TheCall, 2, BuiltinID))
2572  return ExprError();
2573  break;
2574  case Builtin::BI__builtin_isfinite:
2575  case Builtin::BI__builtin_isinf:
2576  case Builtin::BI__builtin_isinf_sign:
2577  case Builtin::BI__builtin_isnan:
2578  case Builtin::BI__builtin_issignaling:
2579  case Builtin::BI__builtin_isnormal:
2580  case Builtin::BI__builtin_issubnormal:
2581  case Builtin::BI__builtin_iszero:
2582  case Builtin::BI__builtin_signbit:
2583  case Builtin::BI__builtin_signbitf:
2584  case Builtin::BI__builtin_signbitl:
2585  if (BuiltinFPClassification(TheCall, 1, BuiltinID))
2586  return ExprError();
2587  break;
2588  case Builtin::BI__builtin_shufflevector:
2589  return BuiltinShuffleVector(TheCall);
2590  // TheCall will be freed by the smart pointer here, but that's fine, since
2591  // BuiltinShuffleVector guts it, but then doesn't release it.
2592  case Builtin::BI__builtin_prefetch:
2593  if (BuiltinPrefetch(TheCall))
2594  return ExprError();
2595  break;
2596  case Builtin::BI__builtin_alloca_with_align:
2597  case Builtin::BI__builtin_alloca_with_align_uninitialized:
2598  if (BuiltinAllocaWithAlign(TheCall))
2599  return ExprError();
2600  [[fallthrough]];
2601  case Builtin::BI__builtin_alloca:
2602  case Builtin::BI__builtin_alloca_uninitialized:
2603  Diag(TheCall->getBeginLoc(), diag::warn_alloca)
2604  << TheCall->getDirectCallee();
2605  break;
2606  case Builtin::BI__arithmetic_fence:
2607  if (BuiltinArithmeticFence(TheCall))
2608  return ExprError();
2609  break;
2610  case Builtin::BI__assume:
2611  case Builtin::BI__builtin_assume:
2612  if (BuiltinAssume(TheCall))
2613  return ExprError();
2614  break;
2615  case Builtin::BI__builtin_assume_aligned:
2616  if (BuiltinAssumeAligned(TheCall))
2617  return ExprError();
2618  break;
2619  case Builtin::BI__builtin_dynamic_object_size:
2620  case Builtin::BI__builtin_object_size:
2621  if (BuiltinConstantArgRange(TheCall, 1, 0, 3))
2622  return ExprError();
2623  break;
2624  case Builtin::BI__builtin_longjmp:
2625  if (BuiltinLongjmp(TheCall))
2626  return ExprError();
2627  break;
2628  case Builtin::BI__builtin_setjmp:
2629  if (BuiltinSetjmp(TheCall))
2630  return ExprError();
2631  break;
2632  case Builtin::BI__builtin_classify_type:
2633  if (checkArgCount(*this, TheCall, 1)) return true;
2634  TheCall->setType(Context.IntTy);
2635  break;
2636  case Builtin::BI__builtin_complex:
2637  if (BuiltinComplex(TheCall))
2638  return ExprError();
2639  break;
2640  case Builtin::BI__builtin_constant_p: {
2641  if (checkArgCount(*this, TheCall, 1)) return true;
2642  ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
2643  if (Arg.isInvalid()) return true;
2644  TheCall->setArg(0, Arg.get());
2645  TheCall->setType(Context.IntTy);
2646  break;
2647  }
2648  case Builtin::BI__builtin_launder:
2649  return BuiltinLaunder(*this, TheCall);
2650  case Builtin::BI__sync_fetch_and_add:
2651  case Builtin::BI__sync_fetch_and_add_1:
2652  case Builtin::BI__sync_fetch_and_add_2:
2653  case Builtin::BI__sync_fetch_and_add_4:
2654  case Builtin::BI__sync_fetch_and_add_8:
2655  case Builtin::BI__sync_fetch_and_add_16:
2656  case Builtin::BI__sync_fetch_and_sub:
2657  case Builtin::BI__sync_fetch_and_sub_1:
2658  case Builtin::BI__sync_fetch_and_sub_2:
2659  case Builtin::BI__sync_fetch_and_sub_4:
2660  case Builtin::BI__sync_fetch_and_sub_8:
2661  case Builtin::BI__sync_fetch_and_sub_16:
2662  case Builtin::BI__sync_fetch_and_or:
2663  case Builtin::BI__sync_fetch_and_or_1:
2664  case Builtin::BI__sync_fetch_and_or_2:
2665  case Builtin::BI__sync_fetch_and_or_4:
2666  case Builtin::BI__sync_fetch_and_or_8:
2667  case Builtin::BI__sync_fetch_and_or_16:
2668  case Builtin::BI__sync_fetch_and_and:
2669  case Builtin::BI__sync_fetch_and_and_1:
2670  case Builtin::BI__sync_fetch_and_and_2:
2671  case Builtin::BI__sync_fetch_and_and_4:
2672  case Builtin::BI__sync_fetch_and_and_8:
2673  case Builtin::BI__sync_fetch_and_and_16:
2674  case Builtin::BI__sync_fetch_and_xor:
2675  case Builtin::BI__sync_fetch_and_xor_1:
2676  case Builtin::BI__sync_fetch_and_xor_2:
2677  case Builtin::BI__sync_fetch_and_xor_4:
2678  case Builtin::BI__sync_fetch_and_xor_8:
2679  case Builtin::BI__sync_fetch_and_xor_16:
2680  case Builtin::BI__sync_fetch_and_nand:
2681  case Builtin::BI__sync_fetch_and_nand_1:
2682  case Builtin::BI__sync_fetch_and_nand_2:
2683  case Builtin::BI__sync_fetch_and_nand_4:
2684  case Builtin::BI__sync_fetch_and_nand_8:
2685  case Builtin::BI__sync_fetch_and_nand_16:
2686  case Builtin::BI__sync_add_and_fetch:
2687  case Builtin::BI__sync_add_and_fetch_1:
2688  case Builtin::BI__sync_add_and_fetch_2:
2689  case Builtin::BI__sync_add_and_fetch_4:
2690  case Builtin::BI__sync_add_and_fetch_8:
2691  case Builtin::BI__sync_add_and_fetch_16:
2692  case Builtin::BI__sync_sub_and_fetch:
2693  case Builtin::BI__sync_sub_and_fetch_1:
2694  case Builtin::BI__sync_sub_and_fetch_2:
2695  case Builtin::BI__sync_sub_and_fetch_4:
2696  case Builtin::BI__sync_sub_and_fetch_8:
2697  case Builtin::BI__sync_sub_and_fetch_16:
2698  case Builtin::BI__sync_and_and_fetch:
2699  case Builtin::BI__sync_and_and_fetch_1:
2700  case Builtin::BI__sync_and_and_fetch_2:
2701  case Builtin::BI__sync_and_and_fetch_4:
2702  case Builtin::BI__sync_and_and_fetch_8:
2703  case Builtin::BI__sync_and_and_fetch_16:
2704  case Builtin::BI__sync_or_and_fetch:
2705  case Builtin::BI__sync_or_and_fetch_1:
2706  case Builtin::BI__sync_or_and_fetch_2:
2707  case Builtin::BI__sync_or_and_fetch_4:
2708  case Builtin::BI__sync_or_and_fetch_8:
2709  case Builtin::BI__sync_or_and_fetch_16:
2710  case Builtin::BI__sync_xor_and_fetch:
2711  case Builtin::BI__sync_xor_and_fetch_1:
2712  case Builtin::BI__sync_xor_and_fetch_2:
2713  case Builtin::BI__sync_xor_and_fetch_4:
2714  case Builtin::BI__sync_xor_and_fetch_8:
2715  case Builtin::BI__sync_xor_and_fetch_16:
2716  case Builtin::BI__sync_nand_and_fetch:
2717  case Builtin::BI__sync_nand_and_fetch_1:
2718  case Builtin::BI__sync_nand_and_fetch_2:
2719  case Builtin::BI__sync_nand_and_fetch_4:
2720  case Builtin::BI__sync_nand_and_fetch_8:
2721  case Builtin::BI__sync_nand_and_fetch_16:
2722  case Builtin::BI__sync_val_compare_and_swap:
2723  case Builtin::BI__sync_val_compare_and_swap_1:
2724  case Builtin::BI__sync_val_compare_and_swap_2:
2725  case Builtin::BI__sync_val_compare_and_swap_4:
2726  case Builtin::BI__sync_val_compare_and_swap_8:
2727  case Builtin::BI__sync_val_compare_and_swap_16:
2728  case Builtin::BI__sync_bool_compare_and_swap:
2729  case Builtin::BI__sync_bool_compare_and_swap_1:
2730  case Builtin::BI__sync_bool_compare_and_swap_2:
2731  case Builtin::BI__sync_bool_compare_and_swap_4:
2732  case Builtin::BI__sync_bool_compare_and_swap_8:
2733  case Builtin::BI__sync_bool_compare_and_swap_16:
2734  case Builtin::BI__sync_lock_test_and_set:
2735  case Builtin::BI__sync_lock_test_and_set_1:
2736  case Builtin::BI__sync_lock_test_and_set_2:
2737  case Builtin::BI__sync_lock_test_and_set_4:
2738  case Builtin::BI__sync_lock_test_and_set_8:
2739  case Builtin::BI__sync_lock_test_and_set_16:
2740  case Builtin::BI__sync_lock_release:
2741  case Builtin::BI__sync_lock_release_1:
2742  case Builtin::BI__sync_lock_release_2:
2743  case Builtin::BI__sync_lock_release_4:
2744  case Builtin::BI__sync_lock_release_8:
2745  case Builtin::BI__sync_lock_release_16:
2746  case Builtin::BI__sync_swap:
2747  case Builtin::BI__sync_swap_1:
2748  case Builtin::BI__sync_swap_2:
2749  case Builtin::BI__sync_swap_4:
2750  case Builtin::BI__sync_swap_8:
2751  case Builtin::BI__sync_swap_16:
2752  return BuiltinAtomicOverloaded(TheCallResult);
2753  case Builtin::BI__sync_synchronize:
2754  Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
2755  << TheCall->getCallee()->getSourceRange();
2756  break;
2757  case Builtin::BI__builtin_nontemporal_load:
2758  case Builtin::BI__builtin_nontemporal_store:
2759  return BuiltinNontemporalOverloaded(TheCallResult);
2760  case Builtin::BI__builtin_memcpy_inline: {
2761  clang::Expr *SizeOp = TheCall->getArg(2);
2762  // We warn about copying to or from `nullptr` pointers when `size` is
2763  // greater than 0. When `size` is value dependent we cannot evaluate its
2764  // value so we bail out.
2765  if (SizeOp->isValueDependent())
2766  break;
2767  if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
2768  CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
2769  CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
2770  }
2771  break;
2772  }
2773  case Builtin::BI__builtin_memset_inline: {
2774  clang::Expr *SizeOp = TheCall->getArg(2);
2775  // We warn about filling to `nullptr` pointers when `size` is greater than
2776  // 0. When `size` is value dependent we cannot evaluate its value so we bail
2777  // out.
2778  if (SizeOp->isValueDependent())
2779  break;
2780  if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
2781  CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
2782  break;
2783  }
2784 #define BUILTIN(ID, TYPE, ATTRS)
2785 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
2786  case Builtin::BI##ID: \
2787  return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
2788 #include "clang/Basic/Builtins.inc"
2789  case Builtin::BI__annotation:
2790  if (BuiltinMSVCAnnotation(*this, TheCall))
2791  return ExprError();
2792  break;
2793  case Builtin::BI__builtin_annotation:
2794  if (BuiltinAnnotation(*this, TheCall))
2795  return ExprError();
2796  break;
2797  case Builtin::BI__builtin_addressof:
2798  if (BuiltinAddressof(*this, TheCall))
2799  return ExprError();
2800  break;
2801  case Builtin::BI__builtin_function_start:
2802  if (BuiltinFunctionStart(*this, TheCall))
2803  return ExprError();
2804  break;
2805  case Builtin::BI__builtin_is_aligned:
2806  case Builtin::BI__builtin_align_up:
2807  case Builtin::BI__builtin_align_down:
2808  if (BuiltinAlignment(*this, TheCall, BuiltinID))
2809  return ExprError();
2810  break;
2811  case Builtin::BI__builtin_add_overflow:
2812  case Builtin::BI__builtin_sub_overflow:
2813  case Builtin::BI__builtin_mul_overflow:
2814  if (BuiltinOverflow(*this, TheCall, BuiltinID))
2815  return ExprError();
2816  break;
2817  case Builtin::BI__builtin_operator_new:
2818  case Builtin::BI__builtin_operator_delete: {
2819  bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
2820  ExprResult Res =
2821  BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
2822  if (Res.isInvalid())
2823  CorrectDelayedTyposInExpr(TheCallResult.get());
2824  return Res;
2825  }
2826  case Builtin::BI__builtin_dump_struct:
2827  return BuiltinDumpStruct(*this, TheCall);
2828  case Builtin::BI__builtin_expect_with_probability: {
2829  // We first want to ensure we are called with 3 arguments
2830  if (checkArgCount(*this, TheCall, 3))
2831  return ExprError();
2832  // then check probability is constant float in range [0.0, 1.0]
2833  const Expr *ProbArg = TheCall->getArg(2);
2835  Expr::EvalResult Eval;
2836  Eval.Diag = &Notes;
2837  if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
2838  !Eval.Val.isFloat()) {
2839  Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
2840  << ProbArg->getSourceRange();
2841  for (const PartialDiagnosticAt &PDiag : Notes)
2842  Diag(PDiag.first, PDiag.second);
2843  return ExprError();
2844  }
2845  llvm::APFloat Probability = Eval.Val.getFloat();
2846  bool LoseInfo = false;
2847  Probability.convert(llvm::APFloat::IEEEdouble(),
2848  llvm::RoundingMode::Dynamic, &LoseInfo);
2849  if (!(Probability >= llvm::APFloat(0.0) &&
2850  Probability <= llvm::APFloat(1.0))) {
2851  Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
2852  << ProbArg->getSourceRange();
2853  return ExprError();
2854  }
2855  break;
2856  }
2857  case Builtin::BI__builtin_preserve_access_index:
2858  if (BuiltinPreserveAI(*this, TheCall))
2859  return ExprError();
2860  break;
2861  case Builtin::BI__builtin_call_with_static_chain:
2862  if (BuiltinCallWithStaticChain(*this, TheCall))
2863  return ExprError();
2864  break;
2865  case Builtin::BI__exception_code:
2866  case Builtin::BI_exception_code:
2867  if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
2868  diag::err_seh___except_block))
2869  return ExprError();
2870  break;
2871  case Builtin::BI__exception_info:
2872  case Builtin::BI_exception_info:
2873  if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
2874  diag::err_seh___except_filter))
2875  return ExprError();
2876  break;
2877  case Builtin::BI__GetExceptionInfo:
2878  if (checkArgCount(*this, TheCall, 1))
2879  return ExprError();
2880 
2881  if (CheckCXXThrowOperand(
2882  TheCall->getBeginLoc(),
2883  Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
2884  TheCall))
2885  return ExprError();
2886 
2887  TheCall->setType(Context.VoidPtrTy);
2888  break;
2889  case Builtin::BIaddressof:
2890  case Builtin::BI__addressof:
2891  case Builtin::BIforward:
2892  case Builtin::BIforward_like:
2893  case Builtin::BImove:
2894  case Builtin::BImove_if_noexcept:
2895  case Builtin::BIas_const: {
2896  // These are all expected to be of the form
2897  // T &/&&/* f(U &/&&)
2898  // where T and U only differ in qualification.
2899  if (checkArgCount(*this, TheCall, 1))
2900  return ExprError();
2901  QualType Param = FDecl->getParamDecl(0)->getType();
2902  QualType Result = FDecl->getReturnType();
2903  bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
2904  BuiltinID == Builtin::BI__addressof;
2905  if (!(Param->isReferenceType() &&
2906  (ReturnsPointer ? Result->isAnyPointerType()
2907  : Result->isReferenceType()) &&
2908  Context.hasSameUnqualifiedType(Param->getPointeeType(),
2909  Result->getPointeeType()))) {
2910  Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
2911  << FDecl;
2912  return ExprError();
2913  }
2914  break;
2915  }
2916  case Builtin::BI__builtin_ptrauth_strip:
2917  return PointerAuthStrip(*this, TheCall);
2918  case Builtin::BI__builtin_ptrauth_blend_discriminator:
2919  return PointerAuthBlendDiscriminator(*this, TheCall);
2920  case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
2921  return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign);
2922  case Builtin::BI__builtin_ptrauth_auth:
2923  return PointerAuthSignOrAuth(*this, TheCall, PAO_Auth);
2924  case Builtin::BI__builtin_ptrauth_sign_generic_data:
2925  return PointerAuthSignGenericData(*this, TheCall);
2926  case Builtin::BI__builtin_ptrauth_auth_and_resign:
2927  return PointerAuthAuthAndResign(*this, TheCall);
2928  // OpenCL v2.0, s6.13.16 - Pipe functions
2929  case Builtin::BIread_pipe:
2930  case Builtin::BIwrite_pipe:
2931  // Since those two functions are declared with var args, we need a semantic
2932  // check for the argument.
2933  if (BuiltinRWPipe(*this, TheCall))
2934  return ExprError();
2935  break;
2936  case Builtin::BIreserve_read_pipe:
2937  case Builtin::BIreserve_write_pipe:
2938  case Builtin::BIwork_group_reserve_read_pipe:
2939  case Builtin::BIwork_group_reserve_write_pipe:
2940  if (BuiltinReserveRWPipe(*this, TheCall))
2941  return ExprError();
2942  break;
2943  case Builtin::BIsub_group_reserve_read_pipe:
2944  case Builtin::BIsub_group_reserve_write_pipe:
2945  if (checkOpenCLSubgroupExt(*this, TheCall) ||
2946  BuiltinReserveRWPipe(*this, TheCall))
2947  return ExprError();
2948  break;
2949  case Builtin::BIcommit_read_pipe:
2950  case Builtin::BIcommit_write_pipe:
2951  case Builtin::BIwork_group_commit_read_pipe:
2952  case Builtin::BIwork_group_commit_write_pipe:
2953  if (BuiltinCommitRWPipe(*this, TheCall))
2954  return ExprError();
2955  break;
2956  case Builtin::BIsub_group_commit_read_pipe:
2957  case Builtin::BIsub_group_commit_write_pipe:
2958  if (checkOpenCLSubgroupExt(*this, TheCall) ||
2959  BuiltinCommitRWPipe(*this, TheCall))
2960  return ExprError();
2961  break;
2962  case Builtin::BIget_pipe_num_packets:
2963  case Builtin::BIget_pipe_max_packets:
2964  if (BuiltinPipePackets(*this, TheCall))
2965  return ExprError();
2966  break;
2967  case Builtin::BIto_global:
2968  case Builtin::BIto_local:
2969  case Builtin::BIto_private:
2970  if (OpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
2971  return ExprError();
2972  break;
2973  // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
2974  case Builtin::BIenqueue_kernel:
2975  if (OpenCLBuiltinEnqueueKernel(*this, TheCall))
2976  return ExprError();
2977  break;
2978  case Builtin::BIget_kernel_work_group_size:
2979  case Builtin::BIget_kernel_preferred_work_group_size_multiple:
2980  if (OpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
2981  return ExprError();
2982  break;
2983  case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
2984  case Builtin::BIget_kernel_sub_group_count_for_ndrange:
2985  if (OpenCLBuiltinNDRangeAndBlock(*this, TheCall))
2986  return ExprError();
2987  break;
2988  case Builtin::BI__builtin_os_log_format:
2989  Cleanup.setExprNeedsCleanups(true);
2990  [[fallthrough]];
2991  case Builtin::BI__builtin_os_log_format_buffer_size:
2992  if (BuiltinOSLogFormat(TheCall))
2993  return ExprError();
2994  break;
2995  case Builtin::BI__builtin_intel_fpga_reg:
2996  if (!Context.getLangOpts().SYCLIsDevice) {
2997  Diag(TheCall->getBeginLoc(), diag::err_builtin_requires_language)
2998  << "__builtin_intel_fpga_reg"
2999  << "SYCL device";
3000  return ExprError();
3001  }
3002  if (CheckIntelFPGARegBuiltinFunctionCall(BuiltinID, TheCall))
3003  return ExprError();
3004  break;
3005  case Builtin::BI__builtin_intel_sycl_ptr_annotation:
3006  if (!Context.getLangOpts().SYCLIsDevice) {
3007  Diag(TheCall->getBeginLoc(), diag::err_builtin_requires_language)
3008  << "__builtin_intel_sycl_ptr_annotation"
3009  << "SYCL device";
3010  return ExprError();
3011  }
3012  if (CheckIntelSYCLPtrAnnotationBuiltinFunctionCall(BuiltinID, TheCall))
3013  return ExprError();
3014  break;
3015  case Builtin::BI__builtin_intel_sycl_alloca:
3016  case Builtin::BI__builtin_intel_sycl_alloca_with_align:
3017  if (!Context.getLangOpts().SYCLIsDevice) {
3018  Diag(TheCall->getBeginLoc(), diag::err_builtin_requires_language)
3019  << (BuiltinID == Builtin::BI__builtin_intel_sycl_alloca
3020  ? "__builtin_intel_sycl_alloca"
3021  : "__builtin_intel_sycl_alloca_with_align")
3022  << "SYCL device";
3023  return ExprError();
3024  }
3025  if (getASTContext().getTargetInfo().getTriple().isSPIRAOT()) {
3026  Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported);
3027  Diag(TheCall->getBeginLoc(), diag::note_intel_sycl_alloca_aot)
3028  << (BuiltinID == Builtin::BI__builtin_intel_sycl_alloca_with_align);
3029  return ExprError();
3030  }
3031  if (CheckIntelSYCLAllocaBuiltinFunctionCall(BuiltinID, TheCall))
3032  return ExprError();
3033  break;
3034  case Builtin::BI__builtin_intel_fpga_mem:
3035  if (!Context.getLangOpts().SYCLIsDevice) {
3036  Diag(TheCall->getBeginLoc(), diag::err_builtin_requires_language)
3037  << "__builtin_intel_fpga_mem"
3038  << "SYCL device";
3039  return ExprError();
3040  }
3041  if (CheckIntelFPGAMemBuiltinFunctionCall(TheCall))
3042  return ExprError();
3043  break;
3044  case Builtin::BI__builtin_frame_address:
3045  case Builtin::BI__builtin_return_address: {
3046  if (BuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
3047  return ExprError();
3048 
3049  // -Wframe-address warning if non-zero passed to builtin
3050  // return/frame address.
3051  Expr::EvalResult Result;
3052  if (!TheCall->getArg(0)->isValueDependent() &&
3053  TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
3054  Result.Val.getInt() != 0)
3055  Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
3056  << ((BuiltinID == Builtin::BI__builtin_return_address)
3057  ? "__builtin_return_address"
3058  : "__builtin_frame_address")
3059  << TheCall->getSourceRange();
3060  break;
3061  }
3062 
3063  case Builtin::BI__builtin_nondeterministic_value: {
3064  if (BuiltinNonDeterministicValue(TheCall))
3065  return ExprError();
3066  break;
3067  }
3068 
3069  // __builtin_elementwise_abs restricts the element type to signed integers or
3070  // floating point types only.
3071  case Builtin::BI__builtin_elementwise_abs: {
3072  if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
3073  return ExprError();
3074 
3075  QualType ArgTy = TheCall->getArg(0)->getType();
3076  QualType EltTy = ArgTy;
3077 
3078  if (auto *VecTy = EltTy->getAs<VectorType>())
3079  EltTy = VecTy->getElementType();
3080  if (EltTy->isUnsignedIntegerType()) {
3081  Diag(TheCall->getArg(0)->getBeginLoc(),
3082  diag::err_builtin_invalid_arg_type)
3083  << 1 << /* signed integer or float ty*/ 3 << ArgTy;
3084  return ExprError();
3085  }
3086  break;
3087  }
3088 
3089  // These builtins restrict the element type to floating point
3090  // types only.
3091  case Builtin::BI__builtin_elementwise_ceil:
3092  case Builtin::BI__builtin_elementwise_cos:
3093  case Builtin::BI__builtin_elementwise_exp:
3094  case Builtin::BI__builtin_elementwise_exp2:
3095  case Builtin::BI__builtin_elementwise_floor:
3096  case Builtin::BI__builtin_elementwise_log:
3097  case Builtin::BI__builtin_elementwise_log2:
3098  case Builtin::BI__builtin_elementwise_log10:
3099  case Builtin::BI__builtin_elementwise_roundeven:
3100  case Builtin::BI__builtin_elementwise_round:
3101  case Builtin::BI__builtin_elementwise_rint:
3102  case Builtin::BI__builtin_elementwise_nearbyint:
3103  case Builtin::BI__builtin_elementwise_sin:
3104  case Builtin::BI__builtin_elementwise_sqrt:
3105  case Builtin::BI__builtin_elementwise_trunc:
3106  case Builtin::BI__builtin_elementwise_canonicalize: {
3107  if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
3108  return ExprError();
3109 
3110  QualType ArgTy = TheCall->getArg(0)->getType();
3111  if (checkFPMathBuiltinElementType(*this, TheCall->getArg(0)->getBeginLoc(),
3112  ArgTy, 1))
3113  return ExprError();
3114  break;
3115  }
3116  case Builtin::BI__builtin_elementwise_fma: {
3117  if (BuiltinElementwiseTernaryMath(TheCall))
3118  return ExprError();
3119  break;
3120  }
3121 
3122  // These builtins restrict the element type to floating point
3123  // types only, and take in two arguments.
3124  case Builtin::BI__builtin_elementwise_pow: {
3125  if (BuiltinElementwiseMath(TheCall))
3126  return ExprError();
3127 
3128  QualType ArgTy = TheCall->getArg(0)->getType();
3129  if (checkFPMathBuiltinElementType(*this, TheCall->getArg(0)->getBeginLoc(),
3130  ArgTy, 1) ||
3131  checkFPMathBuiltinElementType(*this, TheCall->getArg(1)->getBeginLoc(),
3132  ArgTy, 2))
3133  return ExprError();
3134  break;
3135  }
3136 
3137  // These builtins restrict the element type to integer
3138  // types only.
3139  case Builtin::BI__builtin_elementwise_add_sat:
3140  case Builtin::BI__builtin_elementwise_sub_sat: {
3141  if (BuiltinElementwiseMath(TheCall))
3142  return ExprError();
3143 
3144  const Expr *Arg = TheCall->getArg(0);
3145  QualType ArgTy = Arg->getType();
3146  QualType EltTy = ArgTy;
3147 
3148  if (auto *VecTy = EltTy->getAs<VectorType>())
3149  EltTy = VecTy->getElementType();
3150 
3151  if (!EltTy->isIntegerType()) {
3152  Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3153  << 1 << /* integer ty */ 6 << ArgTy;
3154  return ExprError();
3155  }
3156  break;
3157  }
3158 
3159  case Builtin::BI__builtin_elementwise_min:
3160  case Builtin::BI__builtin_elementwise_max:
3161  if (BuiltinElementwiseMath(TheCall))
3162  return ExprError();
3163  break;
3164 
3165  case Builtin::BI__builtin_elementwise_bitreverse: {
3166  if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
3167  return ExprError();
3168 
3169  const Expr *Arg = TheCall->getArg(0);
3170  QualType ArgTy = Arg->getType();
3171  QualType EltTy = ArgTy;
3172 
3173  if (auto *VecTy = EltTy->getAs<VectorType>())
3174  EltTy = VecTy->getElementType();
3175 
3176  if (!EltTy->isIntegerType()) {
3177  Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3178  << 1 << /* integer ty */ 6 << ArgTy;
3179  return ExprError();
3180  }
3181  break;
3182  }
3183 
3184  case Builtin::BI__builtin_elementwise_copysign: {
3185  if (checkArgCount(*this, TheCall, 2))
3186  return ExprError();
3187 
3188  ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
3189  ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
3190  if (Magnitude.isInvalid() || Sign.isInvalid())
3191  return ExprError();
3192 
3193  QualType MagnitudeTy = Magnitude.get()->getType();
3194  QualType SignTy = Sign.get()->getType();
3195  if (checkFPMathBuiltinElementType(*this, TheCall->getArg(0)->getBeginLoc(),
3196  MagnitudeTy, 1) ||
3197  checkFPMathBuiltinElementType(*this, TheCall->getArg(1)->getBeginLoc(),
3198  SignTy, 2)) {
3199  return ExprError();
3200  }
3201 
3202  if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
3203  return Diag(Sign.get()->getBeginLoc(),
3204  diag::err_typecheck_call_different_arg_types)
3205  << MagnitudeTy << SignTy;
3206  }
3207 
3208  TheCall->setArg(0, Magnitude.get());
3209  TheCall->setArg(1, Sign.get());
3210  TheCall->setType(Magnitude.get()->getType());
3211  break;
3212  }
3213  case Builtin::BI__builtin_reduce_max:
3214  case Builtin::BI__builtin_reduce_min: {
3215  if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3216  return ExprError();
3217 
3218  const Expr *Arg = TheCall->getArg(0);
3219  const auto *TyA = Arg->getType()->getAs<VectorType>();
3220  if (!TyA) {
3221  Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3222  << 1 << /* vector ty*/ 4 << Arg->getType();
3223  return ExprError();
3224  }
3225 
3226  TheCall->setType(TyA->getElementType());
3227  break;
3228  }
3229 
3230  // These builtins support vectors of integers only.
3231  // TODO: ADD/MUL should support floating-point types.
3232  case Builtin::BI__builtin_reduce_add:
3233  case Builtin::BI__builtin_reduce_mul:
3234  case Builtin::BI__builtin_reduce_xor:
3235  case Builtin::BI__builtin_reduce_or:
3236  case Builtin::BI__builtin_reduce_and: {
3237  if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3238  return ExprError();
3239 
3240  const Expr *Arg = TheCall->getArg(0);
3241  const auto *TyA = Arg->getType()->getAs<VectorType>();
3242  if (!TyA || !TyA->getElementType()->isIntegerType()) {
3243  Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3244  << 1 << /* vector of integers */ 6 << Arg->getType();
3245  return ExprError();
3246  }
3247  TheCall->setType(TyA->getElementType());
3248  break;
3249  }
3250 
3251  case Builtin::BI__builtin_matrix_transpose:
3252  return BuiltinMatrixTranspose(TheCall, TheCallResult);
3253 
3254  case Builtin::BI__builtin_matrix_column_major_load:
3255  return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
3256 
3257  case Builtin::BI__builtin_matrix_column_major_store:
3258  return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
3259 
3260  case Builtin::BI__builtin_get_device_side_mangled_name: {
3261  auto Check = [](CallExpr *TheCall) {
3262  if (TheCall->getNumArgs() != 1)
3263  return false;
3264  auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
3265  if (!DRE)
3266  return false;
3267  auto *D = DRE->getDecl();
3268  if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
3269  return false;
3270  return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3271  D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
3272  };
3273  if (!Check(TheCall)) {
3274  Diag(TheCall->getBeginLoc(),
3275  diag::err_hip_invalid_args_builtin_mangled_name);
3276  return ExprError();
3277  }
3278  break;
3279  }
3280  case Builtin::BI__builtin_popcountg:
3281  if (BuiltinPopcountg(*this, TheCall))
3282  return ExprError();
3283  break;
3284  case Builtin::BI__builtin_clzg:
3285  case Builtin::BI__builtin_ctzg:
3286  if (BuiltinCountZeroBitsGeneric(*this, TheCall))
3287  return ExprError();
3288  break;
3289 
3290  case Builtin::BI__builtin_allow_runtime_check: {
3291  Expr *Arg = TheCall->getArg(0);
3292  // Check if the argument is a string literal.
3293  if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) {
3294  Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3295  << Arg->getSourceRange();
3296  return ExprError();
3297  }
3298  break;
3299  }
3300  }
3301 
3302  if (getLangOpts().HLSL && CheckHLSLBuiltinFunctionCall(BuiltinID, TheCall))
3303  return ExprError();
3304 
3305  // Since the target specific builtins for each arch overlap, only check those
3306  // of the arch we are compiling for.
3307  if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
3308  if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
3309  assert(Context.getAuxTargetInfo() &&
3310  "Aux Target Builtin, but not an aux target?");
3311 
3312  if (CheckTSBuiltinFunctionCall(
3313  *Context.getAuxTargetInfo(),
3314  Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
3315  return ExprError();
3316 
3317  // Detect when host builtins are used in device code only
3318  if (getLangOpts().SYCLIsDevice)
3319  SYCL().DiagIfDeviceCode(TheCall->getBeginLoc(),
3320  diag::err_builtin_target_unsupported);
3321  } else {
3322  if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
3323  TheCall))
3324  return ExprError();
3325  }
3326  }
3327 
3328  return TheCallResult;
3329 }
3330 
3331 // Get the valid immediate range for the specified NEON type code.
3332 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
3333  NeonTypeFlags Type(t);
3334  int IsQuad = ForceQuad ? true : Type.isQuad();
3335  switch (Type.getEltType()) {
3336  case NeonTypeFlags::Int8:
3337  case NeonTypeFlags::Poly8:
3338  return shift ? 7 : (8 << IsQuad) - 1;
3339  case NeonTypeFlags::Int16:
3340  case NeonTypeFlags::Poly16:
3341  return shift ? 15 : (4 << IsQuad) - 1;
3342  case NeonTypeFlags::Int32:
3343  return shift ? 31 : (2 << IsQuad) - 1;
3344  case NeonTypeFlags::Int64:
3345  case NeonTypeFlags::Poly64:
3346  return shift ? 63 : (1 << IsQuad) - 1;
3348  return shift ? 127 : (1 << IsQuad) - 1;
3350  assert(!shift && "cannot shift float types!");
3351  return (4 << IsQuad) - 1;
3353  assert(!shift && "cannot shift float types!");
3354  return (2 << IsQuad) - 1;
3356  assert(!shift && "cannot shift float types!");
3357  return (1 << IsQuad) - 1;
3359  assert(!shift && "cannot shift float types!");
3360  return (4 << IsQuad) - 1;
3361  }
3362  llvm_unreachable("Invalid NeonTypeFlag!");
3363 }
3364 
3365 /// getNeonEltType - Return the QualType corresponding to the elements of
3366 /// the vector type specified by the NeonTypeFlags. This is used to check
3367 /// the pointer arguments for Neon load/store intrinsics.
3369  bool IsPolyUnsigned, bool IsInt64Long) {
3370  switch (Flags.getEltType()) {
3371  case NeonTypeFlags::Int8:
3372  return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
3373  case NeonTypeFlags::Int16:
3374  return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
3375  case NeonTypeFlags::Int32:
3376  return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
3377  case NeonTypeFlags::Int64:
3378  if (IsInt64Long)
3379  return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
3380  else
3381  return Flags.isUnsigned() ? Context.UnsignedLongLongTy
3382  : Context.LongLongTy;
3383  case NeonTypeFlags::Poly8:
3384  return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
3385  case NeonTypeFlags::Poly16:
3386  return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
3387  case NeonTypeFlags::Poly64:
3388  if (IsInt64Long)
3389  return Context.UnsignedLongTy;
3390  else
3391  return Context.UnsignedLongLongTy;
3393  break;
3395  return Context.HalfTy;
3397  return Context.FloatTy;
3399  return Context.DoubleTy;
3401  return Context.BFloat16Ty;
3402  }
3403  llvm_unreachable("Invalid NeonTypeFlag!");
3404 }
3405 
3411 };
3412 
3413 enum ArmSMEState : unsigned {
3415 
3416  ArmInZA = 0b01,
3417  ArmOutZA = 0b10,
3418  ArmInOutZA = 0b11,
3419  ArmZAMask = 0b11,
3420 
3421  ArmInZT0 = 0b01 << 2,
3422  ArmOutZT0 = 0b10 << 2,
3423  ArmInOutZT0 = 0b11 << 2,
3424  ArmZT0Mask = 0b11 << 2
3425 };
3426 
3427 bool Sema::ParseSVEImmChecks(
3428  CallExpr *TheCall, SmallVector<std::tuple<int, int, int>, 3> &ImmChecks) {
3429  // Perform all the immediate checks for this builtin call.
3430  bool HasError = false;
3431  for (auto &I : ImmChecks) {
3432  int ArgNum, CheckTy, ElementSizeInBits;
3433  std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
3434 
3435  typedef bool (*OptionSetCheckFnTy)(int64_t Value);
3436 
3437  // Function that checks whether the operand (ArgNum) is an immediate
3438  // that is one of the predefined values.
3439  auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
3440  int ErrDiag) -> bool {
3441  // We can't check the value of a dependent argument.
3442  Expr *Arg = TheCall->getArg(ArgNum);
3443  if (Arg->isTypeDependent() || Arg->isValueDependent())
3444  return false;
3445 
3446  // Check constant-ness first.
3447  llvm::APSInt Imm;
3448  if (BuiltinConstantArg(TheCall, ArgNum, Imm))
3449  return true;
3450 
3451  if (!CheckImm(Imm.getSExtValue()))
3452  return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
3453  return false;
3454  };
3455 
3456  switch ((SVETypeFlags::ImmCheckType)CheckTy) {
3457  case SVETypeFlags::ImmCheck0_31:
3458  if (BuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
3459  HasError = true;
3460  break;
3461  case SVETypeFlags::ImmCheck0_13:
3462  if (BuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
3463  HasError = true;
3464  break;
3465  case SVETypeFlags::ImmCheck1_16:
3466  if (BuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
3467  HasError = true;
3468  break;
3469  case SVETypeFlags::ImmCheck0_7:
3470  if (BuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
3471  HasError = true;
3472  break;
3473  case SVETypeFlags::ImmCheck1_1:
3474  if (BuiltinConstantArgRange(TheCall, ArgNum, 1, 1))
3475  HasError = true;
3476  break;
3477  case SVETypeFlags::ImmCheck1_3:
3478  if (BuiltinConstantArgRange(TheCall, ArgNum, 1, 3))
3479  HasError = true;
3480  break;
3481  case SVETypeFlags::ImmCheck1_7:
3482  if (BuiltinConstantArgRange(TheCall, ArgNum, 1, 7))
3483  HasError = true;
3484  break;
3485  case SVETypeFlags::ImmCheckExtract:
3486  if (BuiltinConstantArgRange(TheCall, ArgNum, 0,
3487  (2048 / ElementSizeInBits) - 1))
3488  HasError = true;
3489  break;
3490  case SVETypeFlags::ImmCheckShiftRight:
3491  if (BuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
3492  HasError = true;
3493  break;
3494  case SVETypeFlags::ImmCheckShiftRightNarrow:
3495  if (BuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits / 2))
3496  HasError = true;
3497  break;
3498  case SVETypeFlags::ImmCheckShiftLeft:
3499  if (BuiltinConstantArgRange(TheCall, ArgNum, 0, ElementSizeInBits - 1))
3500  HasError = true;
3501  break;
3502  case SVETypeFlags::ImmCheckLaneIndex:
3503  if (BuiltinConstantArgRange(TheCall, ArgNum, 0,
3504  (128 / (1 * ElementSizeInBits)) - 1))
3505  HasError = true;
3506  break;
3507  case SVETypeFlags::ImmCheckLaneIndexCompRotate:
3508  if (BuiltinConstantArgRange(TheCall, ArgNum, 0,
3509  (128 / (2 * ElementSizeInBits)) - 1))
3510  HasError = true;
3511  break;
3512  case SVETypeFlags::ImmCheckLaneIndexDot:
3513  if (BuiltinConstantArgRange(TheCall, ArgNum, 0,
3514  (128 / (4 * ElementSizeInBits)) - 1))
3515  HasError = true;
3516  break;
3517  case SVETypeFlags::ImmCheckComplexRot90_270:
3518  if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
3519  diag::err_rotation_argument_to_cadd))
3520  HasError = true;
3521  break;
3522  case SVETypeFlags::ImmCheckComplexRotAll90:
3523  if (CheckImmediateInSet(
3524  [](int64_t V) {
3525  return V == 0 || V == 90 || V == 180 || V == 270;
3526  },
3527  diag::err_rotation_argument_to_cmla))
3528  HasError = true;
3529  break;
3530  case SVETypeFlags::ImmCheck0_1:
3531  if (BuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
3532  HasError = true;
3533  break;
3534  case SVETypeFlags::ImmCheck0_2:
3535  if (BuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
3536  HasError = true;
3537  break;
3538  case SVETypeFlags::ImmCheck0_3:
3539  if (BuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
3540  HasError = true;
3541  break;
3542  case SVETypeFlags::ImmCheck0_0:
3543  if (BuiltinConstantArgRange(TheCall, ArgNum, 0, 0))
3544  HasError = true;
3545  break;
3546  case SVETypeFlags::ImmCheck0_15:
3547  if (BuiltinConstantArgRange(TheCall, ArgNum, 0, 15))
3548  HasError = true;
3549  break;
3550  case SVETypeFlags::ImmCheck0_255:
3551  if (BuiltinConstantArgRange(TheCall, ArgNum, 0, 255))
3552  HasError = true;
3553  break;
3554  case SVETypeFlags::ImmCheck2_4_Mul2:
3555  if (BuiltinConstantArgRange(TheCall, ArgNum, 2, 4) ||
3556  BuiltinConstantArgMultiple(TheCall, ArgNum, 2))
3557  HasError = true;
3558  break;
3559  }
3560  }
3561 
3562  return HasError;
3563 }
3564 
3566  if (FD->hasAttr<ArmLocallyStreamingAttr>())
3567  return ArmStreaming;
3568  if (const Type *Ty = FD->getType().getTypePtrOrNull()) {
3569  if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
3570  if (FPT->getAArch64SMEAttributes() &
3572  return ArmStreaming;
3573  if (FPT->getAArch64SMEAttributes() &
3575  return ArmStreamingCompatible;
3576  }
3577  }
3578  return ArmNonStreaming;
3579 }
3580 
3581 static void checkArmStreamingBuiltin(Sema &S, CallExpr *TheCall,
3582  const FunctionDecl *FD,
3586  // Check intrinsics that are available in [sve2p1 or sme/sme2].
3587  llvm::StringMap<bool> CallerFeatureMap;
3588  S.Context.getFunctionFeatureMap(CallerFeatureMap, FD);
3589  if (Builtin::evaluateRequiredTargetFeatures("sve2p1", CallerFeatureMap))
3591  else
3593  }
3594 
3595  if (FnType == ArmStreaming && BuiltinType == ArmNonStreaming) {
3596  S.Diag(TheCall->getBeginLoc(), diag::warn_attribute_arm_sm_incompat_builtin)
3597  << TheCall->getSourceRange() << "streaming";
3598  }
3599 
3600  if (FnType == ArmStreamingCompatible &&
3602  S.Diag(TheCall->getBeginLoc(), diag::warn_attribute_arm_sm_incompat_builtin)
3603  << TheCall->getSourceRange() << "streaming compatible";
3604  return;
3605  }
3606 
3607  if (FnType == ArmNonStreaming && BuiltinType == ArmStreaming) {
3608  S.Diag(TheCall->getBeginLoc(), diag::warn_attribute_arm_sm_incompat_builtin)
3609  << TheCall->getSourceRange() << "non-streaming";
3610  }
3611 }
3612 
3613 static bool hasArmZAState(const FunctionDecl *FD) {
3614  const auto *T = FD->getType()->getAs<FunctionProtoType>();
3617  (FD->hasAttr<ArmNewAttr>() && FD->getAttr<ArmNewAttr>()->isNewZA());
3618 }
3619 
3620 static bool hasArmZT0State(const FunctionDecl *FD) {
3621  const auto *T = FD->getType()->getAs<FunctionProtoType>();
3624  (FD->hasAttr<ArmNewAttr>() && FD->getAttr<ArmNewAttr>()->isNewZT0());
3625 }
3626 
3627 static ArmSMEState getSMEState(unsigned BuiltinID) {
3628  switch (BuiltinID) {
3629  default:
3630  return ArmNoState;
3631 #define GET_SME_BUILTIN_GET_STATE
3632 #include "clang/Basic/arm_sme_builtins_za_state.inc"
3633 #undef GET_SME_BUILTIN_GET_STATE
3634  }
3635 }
3636 
3637 bool Sema::CheckSMEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3638  if (const FunctionDecl *FD = getCurFunctionDecl()) {
3639  std::optional<ArmStreamingType> BuiltinType;
3640 
3641  switch (BuiltinID) {
3642 #define GET_SME_STREAMING_ATTRS
3643 #include "clang/Basic/arm_sme_streaming_attrs.inc"
3644 #undef GET_SME_STREAMING_ATTRS
3645  }
3646 
3647  if (BuiltinType)
3648  checkArmStreamingBuiltin(*this, TheCall, FD, *BuiltinType);
3649 
3650  if ((getSMEState(BuiltinID) & ArmZAMask) && !hasArmZAState(FD))
3651  Diag(TheCall->getBeginLoc(),
3652  diag::warn_attribute_arm_za_builtin_no_za_state)
3653  << TheCall->getSourceRange();
3654 
3655  if ((getSMEState(BuiltinID) & ArmZT0Mask) && !hasArmZT0State(FD))
3656  Diag(TheCall->getBeginLoc(),
3657  diag::warn_attribute_arm_zt0_builtin_no_zt0_state)
3658  << TheCall->getSourceRange();
3659  }
3660 
3661  // Range check SME intrinsics that take immediate values.
3663 
3664  switch (BuiltinID) {
3665  default:
3666  return false;
3667 #define GET_SME_IMMEDIATE_CHECK
3668 #include "clang/Basic/arm_sme_sema_rangechecks.inc"
3669 #undef GET_SME_IMMEDIATE_CHECK
3670  }
3671 
3672  return ParseSVEImmChecks(TheCall, ImmChecks);
3673 }
3674 
3675 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3676  if (const FunctionDecl *FD = getCurFunctionDecl()) {
3677  std::optional<ArmStreamingType> BuiltinType;
3678 
3679  switch (BuiltinID) {
3680 #define GET_SVE_STREAMING_ATTRS
3681 #include "clang/Basic/arm_sve_streaming_attrs.inc"
3682 #undef GET_SVE_STREAMING_ATTRS
3683  }
3684  if (BuiltinType)
3685  checkArmStreamingBuiltin(*this, TheCall, FD, *BuiltinType);
3686  }
3687  // Range check SVE intrinsics that take immediate values.
3689 
3690  switch (BuiltinID) {
3691  default:
3692  return false;
3693 #define GET_SVE_IMMEDIATE_CHECK
3694 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
3695 #undef GET_SVE_IMMEDIATE_CHECK
3696  }
3697 
3698  return ParseSVEImmChecks(TheCall, ImmChecks);
3699 }
3700 
3701 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
3702  unsigned BuiltinID, CallExpr *TheCall) {
3703  if (const FunctionDecl *FD = getCurFunctionDecl()) {
3704 
3705  switch (BuiltinID) {
3706  default:
3707  break;
3708 #define GET_NEON_BUILTINS
3709 #define TARGET_BUILTIN(id, ...) case NEON::BI##id:
3710 #define BUILTIN(id, ...) case NEON::BI##id:
3711 #include "clang/Basic/arm_neon.inc"
3712  checkArmStreamingBuiltin(*this, TheCall, FD, ArmNonStreaming);
3713  break;
3714 #undef TARGET_BUILTIN
3715 #undef BUILTIN
3716 #undef GET_NEON_BUILTINS
3717  }
3718  }
3719 
3720  llvm::APSInt Result;
3721  uint64_t mask = 0;
3722  unsigned TV = 0;
3723  int PtrArgNum = -1;
3724  bool HasConstPtr = false;
3725  switch (BuiltinID) {
3726 #define GET_NEON_OVERLOAD_CHECK
3727 #include "clang/Basic/arm_neon.inc"
3728 #include "clang/Basic/arm_fp16.inc"
3729 #undef GET_NEON_OVERLOAD_CHECK
3730  }
3731 
3732  // For NEON intrinsics which are overloaded on vector element type, validate
3733  // the immediate which specifies which variant to emit.
3734  unsigned ImmArg = TheCall->getNumArgs()-1;
3735  if (mask) {
3736  if (BuiltinConstantArg(TheCall, ImmArg, Result))
3737  return true;
3738 
3739  TV = Result.getLimitedValue(64);
3740  if ((TV > 63) || (mask & (1ULL << TV)) == 0)
3741  return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
3742  << TheCall->getArg(ImmArg)->getSourceRange();
3743  }
3744 
3745  if (PtrArgNum >= 0) {
3746  // Check that pointer arguments have the specified type.
3747  Expr *Arg = TheCall->getArg(PtrArgNum);
3748  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
3749  Arg = ICE->getSubExpr();
3750  ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
3751  QualType RHSTy = RHS.get()->getType();
3752 
3753  llvm::Triple::ArchType Arch = TI.getTriple().getArch();
3754  bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
3755  Arch == llvm::Triple::aarch64_32 ||
3756  Arch == llvm::Triple::aarch64_be;
3757  bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
3758  QualType EltTy =
3759  getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
3760  if (HasConstPtr)
3761  EltTy = EltTy.withConst();
3762  QualType LHSTy = Context.getPointerType(EltTy);
3763  AssignConvertType ConvTy;
3764  ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
3765  if (RHS.isInvalid())
3766  return true;
3767  if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
3768  RHS.get(), AA_Assigning))
3769  return true;
3770  }
3771 
3772  // For NEON intrinsics which take an immediate value as part of the
3773  // instruction, range check them here.
3774  unsigned i = 0, l = 0, u = 0;
3775  switch (BuiltinID) {
3776  default:
3777  return false;
3778  #define GET_NEON_IMMEDIATE_CHECK
3779  #include "clang/Basic/arm_neon.inc"
3780  #include "clang/Basic/arm_fp16.inc"
3781  #undef GET_NEON_IMMEDIATE_CHECK
3782  }
3783 
3784  return BuiltinConstantArgRange(TheCall, i, l, u + l);
3785 }
3786 
3787 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3788  switch (BuiltinID) {
3789  default:
3790  return false;
3791  #include "clang/Basic/arm_mve_builtin_sema.inc"
3792  }
3793 }
3794 
3795 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3796  CallExpr *TheCall) {
3797  bool Err = false;
3798  switch (BuiltinID) {
3799  default:
3800  return false;
3801 #include "clang/Basic/arm_cde_builtin_sema.inc"
3802  }
3803 
3804  if (Err)
3805  return true;
3806 
3807  return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
3808 }
3809 
3810 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
3811  const Expr *CoprocArg, bool WantCDE) {
3812  if (isConstantEvaluatedContext())
3813  return false;
3814 
3815  // We can't check the value of a dependent argument.
3816  if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
3817  return false;
3818 
3819  llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
3820  int64_t CoprocNo = CoprocNoAP.getExtValue();
3821  assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
3822 
3823  uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
3824  bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
3825 
3826  if (IsCDECoproc != WantCDE)
3827  return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
3828  << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
3829 
3830  return false;
3831 }
3832 
3833 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
3834  unsigned MaxWidth) {
3835  assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
3836  BuiltinID == ARM::BI__builtin_arm_ldaex ||
3837  BuiltinID == ARM::BI__builtin_arm_strex ||
3838  BuiltinID == ARM::BI__builtin_arm_stlex ||
3839  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
3840  BuiltinID == AArch64::BI__builtin_arm_ldaex ||
3841  BuiltinID == AArch64::BI__builtin_arm_strex ||
3842  BuiltinID == AArch64::BI__builtin_arm_stlex) &&
3843  "unexpected ARM builtin");
3844  bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
3845  BuiltinID == ARM::BI__builtin_arm_ldaex ||
3846  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
3847  BuiltinID == AArch64::BI__builtin_arm_ldaex;
3848 
3849  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3850 
3851  // Ensure that we have the proper number of arguments.
3852  if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
3853  return true;
3854 
3855  // Inspect the pointer argument of the atomic builtin. This should always be
3856  // a pointer type, whose element is an integral scalar or pointer type.
3857  // Because it is a pointer type, we don't have to worry about any implicit
3858  // casts here.
3859  Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
3860  ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
3861  if (PointerArgRes.isInvalid())
3862  return true;
3863  PointerArg = PointerArgRes.get();
3864 
3865  const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3866  if (!pointerType) {
3867  Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
3868  << PointerArg->getType() << PointerArg->getSourceRange();
3869  return true;
3870  }
3871 
3872  // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
3873  // task is to insert the appropriate casts into the AST. First work out just
3874  // what the appropriate type is.
3875  QualType ValType = pointerType->getPointeeType();
3876  QualType AddrType = ValType.getUnqualifiedType().withVolatile();
3877  if (IsLdrex)
3878  AddrType.addConst();
3879 
3880  // Issue a warning if the cast is dodgy.
3881  CastKind CastNeeded = CK_NoOp;
3882  if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
3883  CastNeeded = CK_BitCast;
3884  Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
3885  << PointerArg->getType() << Context.getPointerType(AddrType)
3886  << AA_Passing << PointerArg->getSourceRange();
3887  }
3888 
3889  // Finally, do the cast and replace the argument with the corrected version.
3890  AddrType = Context.getPointerType(AddrType);
3891  PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
3892  if (PointerArgRes.isInvalid())
3893  return true;
3894  PointerArg = PointerArgRes.get();
3895 
3896  TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
3897 
3898  // In general, we allow ints, floats and pointers to be loaded and stored.
3899  if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3900  !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
3901  Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
3902  << PointerArg->getType() << PointerArg->getSourceRange();
3903  return true;
3904  }
3905 
3906  // But ARM doesn't have instructions to deal with 128-bit versions.
3907  if (Context.getTypeSize(ValType) > MaxWidth) {
3908  assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
3909  Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
3910  << PointerArg->getType() << PointerArg->getSourceRange();
3911  return true;
3912  }
3913 
3914  switch (ValType.getObjCLifetime()) {
3915  case Qualifiers::OCL_None:
3917  // okay
3918  break;
3919 
3920  case Qualifiers::OCL_Weak:
3923  Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
3924  << ValType << PointerArg->getSourceRange();
3925  return true;
3926  }
3927 
3928  if (IsLdrex) {
3929  TheCall->setType(ValType);
3930  return false;
3931  }
3932 
3933  // Initialize the argument to be stored.
3934  ExprResult ValArg = TheCall->getArg(0);
3936  Context, ValType, /*consume*/ false);
3937  ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3938  if (ValArg.isInvalid())
3939  return true;
3940  TheCall->setArg(0, ValArg.get());
3941 
3942  // __builtin_arm_strex always returns an int. It's marked as such in the .def,
3943  // but the custom checker bypasses all default analysis.
3944  TheCall->setType(Context.IntTy);
3945  return false;
3946 }
3947 
3948 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3949  CallExpr *TheCall) {
3950  if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
3951  BuiltinID == ARM::BI__builtin_arm_ldaex ||
3952  BuiltinID == ARM::BI__builtin_arm_strex ||
3953  BuiltinID == ARM::BI__builtin_arm_stlex) {
3954  return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
3955  }
3956 
3957  if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
3958  return BuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3959  BuiltinConstantArgRange(TheCall, 2, 0, 1);
3960  }
3961 
3962  if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3963  BuiltinID == ARM::BI__builtin_arm_wsr64)
3964  return BuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
3965 
3966  if (BuiltinID == ARM::BI__builtin_arm_rsr ||
3967  BuiltinID == ARM::BI__builtin_arm_rsrp ||
3968  BuiltinID == ARM::BI__builtin_arm_wsr ||
3969  BuiltinID == ARM::BI__builtin_arm_wsrp)
3970  return BuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
3971 
3972  if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
3973  return true;
3974  if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
3975  return true;
3976  if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
3977  return true;
3978 
3979  // For intrinsics which take an immediate value as part of the instruction,
3980  // range check them here.
3981  // FIXME: VFP Intrinsics should error if VFP not present.
3982  switch (BuiltinID) {
3983  default: return false;
3984  case ARM::BI__builtin_arm_ssat:
3985  return BuiltinConstantArgRange(TheCall, 1, 1, 32);
3986  case ARM::BI__builtin_arm_usat:
3987  return BuiltinConstantArgRange(TheCall, 1, 0, 31);
3988  case ARM::BI__builtin_arm_ssat16:
3989  return BuiltinConstantArgRange(TheCall, 1, 1, 16);
3990  case ARM::BI__builtin_arm_usat16:
3991  return BuiltinConstantArgRange(TheCall, 1, 0, 15);
3992  case ARM::BI__builtin_arm_vcvtr_f:
3993  case ARM::BI__builtin_arm_vcvtr_d:
3994  return BuiltinConstantArgRange(TheCall, 1, 0, 1);
3995  case ARM::BI__builtin_arm_dmb:
3996  case ARM::BI__builtin_arm_dsb:
3997  case ARM::BI__builtin_arm_isb:
3998  case ARM::BI__builtin_arm_dbg:
3999  return BuiltinConstantArgRange(TheCall, 0, 0, 15);
4000  case ARM::BI__builtin_arm_cdp:
4001  case ARM::BI__builtin_arm_cdp2:
4002  case ARM::BI__builtin_arm_mcr:
4003  case ARM::BI__builtin_arm_mcr2:
4004  case ARM::BI__builtin_arm_mrc:
4005  case ARM::BI__builtin_arm_mrc2:
4006  case ARM::BI__builtin_arm_mcrr:
4007  case ARM::BI__builtin_arm_mcrr2:
4008  case ARM::BI__builtin_arm_mrrc:
4009  case ARM::BI__builtin_arm_mrrc2:
4010  case ARM::BI__builtin_arm_ldc:
4011  case ARM::BI__builtin_arm_ldcl:
4012  case ARM::BI__builtin_arm_ldc2:
4013  case ARM::BI__builtin_arm_ldc2l:
4014  case ARM::BI__builtin_arm_stc:
4015  case ARM::BI__builtin_arm_stcl:
4016  case ARM::BI__builtin_arm_stc2:
4017  case ARM::BI__builtin_arm_stc2l:
4018  return BuiltinConstantArgRange(TheCall, 0, 0, 15) ||
4019  CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
4020  /*WantCDE*/ false);
4021  }
4022 }
4023 
4024 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
4025  unsigned BuiltinID,
4026  CallExpr *TheCall) {
4027  if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
4028  BuiltinID == AArch64::BI__builtin_arm_ldaex ||
4029  BuiltinID == AArch64::BI__builtin_arm_strex ||
4030  BuiltinID == AArch64::BI__builtin_arm_stlex) {
4031  return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
4032  }
4033 
4034  if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
4035  return BuiltinConstantArgRange(TheCall, 1, 0, 1) ||
4036  BuiltinConstantArgRange(TheCall, 2, 0, 3) ||
4037  BuiltinConstantArgRange(TheCall, 3, 0, 1) ||
4038  BuiltinConstantArgRange(TheCall, 4, 0, 1);
4039  }
4040 
4041  if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4042  BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4043  BuiltinID == AArch64::BI__builtin_arm_rsr128 ||
4044  BuiltinID == AArch64::BI__builtin_arm_wsr128)
4045  return BuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
4046 
4047  // Memory Tagging Extensions (MTE) Intrinsics
4048  if (BuiltinID == AArch64::BI__builtin_arm_irg ||
4049  BuiltinID == AArch64::BI__builtin_arm_addg ||
4050  BuiltinID == AArch64::BI__builtin_arm_gmi ||
4051  BuiltinID == AArch64::BI__builtin_arm_ldg ||
4052  BuiltinID == AArch64::BI__builtin_arm_stg ||
4053  BuiltinID == AArch64::BI__builtin_arm_subp) {
4054  return BuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
4055  }
4056 
4057  if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
4058  BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4059  BuiltinID == AArch64::BI__builtin_arm_wsr ||
4060  BuiltinID == AArch64::BI__builtin_arm_wsrp)
4061  return BuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
4062 
4063  // Only check the valid encoding range. Any constant in this range would be
4064  // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
4065  // an exception for incorrect registers. This matches MSVC behavior.
4066  if (BuiltinID == AArch64::BI_ReadStatusReg ||
4067  BuiltinID == AArch64::BI_WriteStatusReg)
4068  return BuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
4069 
4070  if (BuiltinID == AArch64::BI__getReg)
4071  return BuiltinConstantArgRange(TheCall, 0, 0, 31);
4072 
4073  if (BuiltinID == AArch64::BI__break)
4074  return BuiltinConstantArgRange(TheCall, 0, 0, 0xffff);
4075 
4076  if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
4077  return true;
4078 
4079  if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
4080  return true;
4081 
4082  if (CheckSMEBuiltinFunctionCall(BuiltinID, TheCall))
4083  return true;
4084 
4085  // For intrinsics which take an immediate value as part of the instruction,
4086  // range check them here.
4087  unsigned i = 0, l = 0, u = 0;
4088  switch (BuiltinID) {
4089  default: return false;
4090  case AArch64::BI__builtin_arm_dmb:
4091  case AArch64::BI__builtin_arm_dsb:
4092  case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
4093  case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
4094  }
4095 
4096  return BuiltinConstantArgRange(TheCall, i, l, u + l);
4097 }
4098 
4100  if (Arg->getType()->getAsPlaceholderType())
4101  return false;
4102 
4103  // The first argument needs to be a record field access.
4104  // If it is an array element access, we delay decision
4105  // to BPF backend to check whether the access is a
4106  // field access or not.
4107  return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
4108  isa<MemberExpr>(Arg->IgnoreParens()) ||
4109  isa<ArraySubscriptExpr>(Arg->IgnoreParens()));
4110 }
4111 
4113  QualType ArgType = Arg->getType();
4114  if (ArgType->getAsPlaceholderType())
4115  return false;
4116 
4117  // for TYPE_EXISTENCE/TYPE_MATCH/TYPE_SIZEOF reloc type
4118  // format:
4119  // 1. __builtin_preserve_type_info(*(<type> *)0, flag);
4120  // 2. <type> var;
4121  // __builtin_preserve_type_info(var, flag);
4122  if (!isa<DeclRefExpr>(Arg->IgnoreParens()) &&
4123  !isa<UnaryOperator>(Arg->IgnoreParens()))
4124  return false;
4125 
4126  // Typedef type.
4127  if (ArgType->getAs<TypedefType>())
4128  return true;
4129 
4130  // Record type or Enum type.
4131  const Type *Ty = ArgType->getUnqualifiedDesugaredType();
4132  if (const auto *RT = Ty->getAs<RecordType>()) {
4133  if (!RT->getDecl()->getDeclName().isEmpty())
4134  return true;
4135  } else if (const auto *ET = Ty->getAs<EnumType>()) {
4136  if (!ET->getDecl()->getDeclName().isEmpty())
4137  return true;
4138  }
4139 
4140  return false;
4141 }
4142 
4144  QualType ArgType = Arg->getType();
4145  if (ArgType->getAsPlaceholderType())
4146  return false;
4147 
4148  // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
4149  // format:
4150  // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
4151  // flag);
4152  const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
4153  if (!UO)
4154  return false;
4155 
4156  const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
4157  if (!CE)
4158  return false;
4159  if (CE->getCastKind() != CK_IntegralToPointer &&
4160  CE->getCastKind() != CK_NullToPointer)
4161  return false;
4162 
4163  // The integer must be from an EnumConstantDecl.
4164  const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
4165  if (!DR)
4166  return false;
4167 
4168  const EnumConstantDecl *Enumerator =
4169  dyn_cast<EnumConstantDecl>(DR->getDecl());
4170  if (!Enumerator)
4171  return false;
4172 
4173  // The type must be EnumType.
4174  const Type *Ty = ArgType->getUnqualifiedDesugaredType();
4175  const auto *ET = Ty->getAs<EnumType>();
4176  if (!ET)
4177  return false;
4178 
4179  // The enum value must be supported.
4180  return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator);
4181 }
4182 
4183 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
4184  CallExpr *TheCall) {
4185  assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
4186  BuiltinID == BPF::BI__builtin_btf_type_id ||
4187  BuiltinID == BPF::BI__builtin_preserve_type_info ||
4188  BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
4189  "unexpected BPF builtin");
4190 
4191  if (checkArgCount(*this, TheCall, 2))
4192  return true;
4193 
4194  // The second argument needs to be a constant int
4195  Expr *Arg = TheCall->getArg(1);
4196  std::optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
4197  diag::kind kind;
4198  if (!Value) {
4199  if (BuiltinID == BPF::BI__builtin_preserve_field_info)
4200  kind = diag::err_preserve_field_info_not_const;
4201  else if (BuiltinID == BPF::BI__builtin_btf_type_id)
4202  kind = diag::err_btf_type_id_not_const;
4203  else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
4204  kind = diag::err_preserve_type_info_not_const;
4205  else
4206  kind = diag::err_preserve_enum_value_not_const;
4207  Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
4208  return true;
4209  }
4210 
4211  // The first argument
4212  Arg = TheCall->getArg(0);
4213  bool InvalidArg = false;
4214  bool ReturnUnsignedInt = true;
4215  if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
4216  if (!isValidBPFPreserveFieldInfoArg(Arg)) {
4217  InvalidArg = true;
4218  kind = diag::err_preserve_field_info_not_field;
4219  }
4220  } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
4221  if (!isValidBPFPreserveTypeInfoArg(Arg)) {
4222  InvalidArg = true;
4223  kind = diag::err_preserve_type_info_invalid;
4224  }
4225  } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
4226  if (!isValidBPFPreserveEnumValueArg(Arg)) {
4227  InvalidArg = true;
4228  kind = diag::err_preserve_enum_value_invalid;
4229  }
4230  ReturnUnsignedInt = false;
4231  } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
4232  ReturnUnsignedInt = false;
4233  }
4234 
4235  if (InvalidArg) {
4236  Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
4237  return true;
4238  }
4239 
4240  if (ReturnUnsignedInt)
4241  TheCall->setType(Context.UnsignedIntTy);
4242  else
4243  TheCall->setType(Context.UnsignedLongTy);
4244  return false;
4245 }
4246 
4247 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
4248  struct ArgInfo {
4249  uint8_t OpNum;
4250  bool IsSigned;
4251  uint8_t BitWidth;
4252  uint8_t Align;
4253  };
4254  struct BuiltinInfo {
4255  unsigned BuiltinID;
4256  ArgInfo Infos[2];
4257  };
4258 
4259  static BuiltinInfo Infos[] = {
4260  { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
4261  { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
4262  { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
4263  { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} },
4264  { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
4265  { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
4266  { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
4267  { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
4268  { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
4269  { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
4270  { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
4271 
4272  { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
4273  { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
4274  { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
4275  { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
4276  { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
4277  { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
4278  { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
4279  { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
4280  { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
4281  { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
4282  { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
4283 
4284  { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
4285  { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
4286  { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
4287  { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
4288  { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
4289  { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
4290  { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
4291  { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
4292  { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
4293  { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
4294  { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
4295  { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
4296  { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
4297  { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
4298  { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
4299  { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
4300  { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
4301  { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
4302  { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
4303  { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
4304  { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
4305  { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
4306  { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
4307  { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
4308  { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
4309  { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
4310  { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
4311  { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
4312  { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
4313  { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
4314  { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
4315  { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
4316  { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
4317  { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
4318  { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
4319  { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
4320  { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
4321  { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
4322  { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
4323  { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
4324  { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
4325  { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
4326  { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
4327  { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
4328  { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
4329  { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
4330  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
4331  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
4332  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
4333  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
4334  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
4335  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
4336  {{ 1, false, 6, 0 }} },
4337  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
4338  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
4339  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
4340  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
4341  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
4342  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
4343  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
4344  {{ 1, false, 5, 0 }} },
4345  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
4346  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
4347  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
4348  { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
4349  { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
4350  { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
4351  { 2, false, 5, 0 }} },
4352  { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
4353  { 2, false, 6, 0 }} },
4354  { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
4355  { 3, false, 5, 0 }} },
4356  { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
4357  { 3, false, 6, 0 }} },
4358  { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
4359  { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
4360  { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
4361  { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
4362  { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
4363  { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
4364  { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
4365  { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
4366  { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
4367  { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
4368  { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
4369  { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
4370  { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
4371  { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
4372  { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
4373  { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
4374  {{ 2, false, 4, 0 },
4375  { 3, false, 5, 0 }} },
4376  { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
4377  {{ 2, false, 4, 0 },
4378  { 3, false, 5, 0 }} },
4379  { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
4380  {{ 2, false, 4, 0 },
4381  { 3, false, 5, 0 }} },
4382  { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
4383  {{ 2, false, 4, 0 },
4384  { 3, false, 5, 0 }} },
4385  { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
4386  { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
4387  { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
4388  { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
4389  { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
4390  { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
4391  { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
4392  { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
4393  { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
4394  { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
4395  { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
4396  { 2, false, 5, 0 }} },
4397  { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
4398  { 2, false, 6, 0 }} },
4399  { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
4400  { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
4401  { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
4402  { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
4403  { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
4404  { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
4405  { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
4406  { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
4407  { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
4408  {{ 1, false, 4, 0 }} },
4409  { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
4410  { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
4411  {{ 1, false, 4, 0 }} },
4412  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
4413  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
4414  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
4415  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
4416  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
4417  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
4418  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
4419  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
4420  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
4421  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
4422  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
4423  { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
4424  { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
4425  { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
4426  { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
4427  { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
4428  { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
4429  { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
4430  { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
4431  { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
4432  {{ 3, false, 1, 0 }} },
4433  { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
4434  { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
4435  { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
4436  { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
4437  {{ 3, false, 1, 0 }} },
4438  { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
4439  { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
4440  { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
4441  { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
4442  {{ 3, false, 1, 0 }} },
4443 
4444  { Hexagon::BI__builtin_HEXAGON_V6_v6mpyhubs10, {{ 2, false, 2, 0 }} },
4445  { Hexagon::BI__builtin_HEXAGON_V6_v6mpyhubs10_128B,
4446  {{ 2, false, 2, 0 }} },
4447  { Hexagon::BI__builtin_HEXAGON_V6_v6mpyhubs10_vxx,
4448  {{ 3, false, 2, 0 }} },
4449  { Hexagon::BI__builtin_HEXAGON_V6_v6mpyhubs10_vxx_128B,
4450  {{ 3, false, 2, 0 }} },
4451  { Hexagon::BI__builtin_HEXAGON_V6_v6mpyvubs10, {{ 2, false, 2, 0 }} },
4452  { Hexagon::BI__builtin_HEXAGON_V6_v6mpyvubs10_128B,
4453  {{ 2, false, 2, 0 }} },
4454  { Hexagon::BI__builtin_HEXAGON_V6_v6mpyvubs10_vxx,
4455  {{ 3, false, 2, 0 }} },
4456  { Hexagon::BI__builtin_HEXAGON_V6_v6mpyvubs10_vxx_128B,
4457  {{ 3, false, 2, 0 }} },
4458  { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, {{ 2, false, 3, 0 }} },
4459  { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, {{ 2, false, 3, 0 }} },
4460  { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, {{ 3, false, 3, 0 }} },
4461  { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B,
4462  {{ 3, false, 3, 0 }} },
4463  { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, {{ 2, false, 3, 0 }} },
4464  { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, {{ 2, false, 3, 0 }} },
4465  { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, {{ 3, false, 3, 0 }} },
4466  { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B,
4467  {{ 3, false, 3, 0 }} },
4468  };
4469 
4470  // Use a dynamically initialized static to sort the table exactly once on
4471  // first run.
4472  static const bool SortOnce =
4473  (llvm::sort(Infos,
4474  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
4475  return LHS.BuiltinID < RHS.BuiltinID;
4476  }),
4477  true);
4478  (void)SortOnce;
4479 
4480  const BuiltinInfo *F = llvm::partition_point(
4481  Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
4482  if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
4483  return false;
4484 
4485  bool Error = false;
4486 
4487  for (const ArgInfo &A : F->Infos) {
4488  // Ignore empty ArgInfo elements.
4489  if (A.BitWidth == 0)
4490  continue;
4491 
4492  int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
4493  int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
4494  if (!A.Align) {
4495  Error |= BuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
4496  } else {
4497  unsigned M = 1 << A.Align;
4498  Min *= M;
4499  Max *= M;
4500  Error |= BuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
4501  Error |= BuiltinConstantArgMultiple(TheCall, A.OpNum, M);
4502  }
4503  }
4504  return Error;
4505 }
4506 
4507 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
4508  CallExpr *TheCall) {
4509  return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
4510 }
4511 
4512 bool Sema::CheckLoongArchBuiltinFunctionCall(const TargetInfo &TI,
4513  unsigned BuiltinID,
4514  CallExpr *TheCall) {
4515  switch (BuiltinID) {
4516  default:
4517  break;
4518  // Basic intrinsics.
4519  case LoongArch::BI__builtin_loongarch_cacop_d:
4520  case LoongArch::BI__builtin_loongarch_cacop_w: {
4521  BuiltinConstantArgRange(TheCall, 0, 0, llvm::maxUIntN(5));
4522  BuiltinConstantArgRange(TheCall, 2, llvm::minIntN(12), llvm::maxIntN(12));
4523  break;
4524  }
4525  case LoongArch::BI__builtin_loongarch_break:
4526  case LoongArch::BI__builtin_loongarch_dbar:
4527  case LoongArch::BI__builtin_loongarch_ibar:
4528  case LoongArch::BI__builtin_loongarch_syscall:
4529  // Check if immediate is in [0, 32767].
4530  return BuiltinConstantArgRange(TheCall, 0, 0, 32767);
4531  case LoongArch::BI__builtin_loongarch_csrrd_w:
4532  case LoongArch::BI__builtin_loongarch_csrrd_d:
4533  return BuiltinConstantArgRange(TheCall, 0, 0, 16383);
4534  case LoongArch::BI__builtin_loongarch_csrwr_w:
4535  case LoongArch::BI__builtin_loongarch_csrwr_d:
4536  return BuiltinConstantArgRange(TheCall, 1, 0, 16383);
4537  case LoongArch::BI__builtin_loongarch_csrxchg_w:
4538  case LoongArch::BI__builtin_loongarch_csrxchg_d:
4539  return BuiltinConstantArgRange(TheCall, 2, 0, 16383);
4540  case LoongArch::BI__builtin_loongarch_lddir_d:
4541  case LoongArch::BI__builtin_loongarch_ldpte_d:
4542  return BuiltinConstantArgRange(TheCall, 1, 0, 31);
4543  case LoongArch::BI__builtin_loongarch_movfcsr2gr:
4544  case LoongArch::BI__builtin_loongarch_movgr2fcsr:
4545  return BuiltinConstantArgRange(TheCall, 0, 0, llvm::maxUIntN(2));
4546 
4547  // LSX intrinsics.
4548  case LoongArch::BI__builtin_lsx_vbitclri_b:
4549  case LoongArch::BI__builtin_lsx_vbitrevi_b:
4550  case LoongArch::BI__builtin_lsx_vbitseti_b:
4551  case LoongArch::BI__builtin_lsx_vsat_b:
4552  case LoongArch::BI__builtin_lsx_vsat_bu:
4553  case LoongArch::BI__builtin_lsx_vslli_b:
4554  case LoongArch::BI__builtin_lsx_vsrai_b:
4555  case LoongArch::BI__builtin_lsx_vsrari_b:
4556  case LoongArch::BI__builtin_lsx_vsrli_b:
4557  case LoongArch::BI__builtin_lsx_vsllwil_h_b:
4558  case LoongArch::BI__builtin_lsx_vsllwil_hu_bu:
4559  case LoongArch::BI__builtin_lsx_vrotri_b:
4560  case LoongArch::BI__builtin_lsx_vsrlri_b:
4561  return BuiltinConstantArgRange(TheCall, 1, 0, 7);
4562  case LoongArch::BI__builtin_lsx_vbitclri_h:
4563  case LoongArch::BI__builtin_lsx_vbitrevi_h:
4564  case LoongArch::BI__builtin_lsx_vbitseti_h:
4565  case LoongArch::BI__builtin_lsx_vsat_h:
4566  case LoongArch::BI__builtin_lsx_vsat_hu:
4567  case LoongArch::BI__builtin_lsx_vslli_h:
4568  case LoongArch::BI__builtin_lsx_vsrai_h:
4569  case LoongArch::BI__builtin_lsx_vsrari_h:
4570  case LoongArch::BI__builtin_lsx_vsrli_h:
4571  case LoongArch::BI__builtin_lsx_vsllwil_w_h:
4572  case LoongArch::BI__builtin_lsx_vsllwil_wu_hu:
4573  case LoongArch::BI__builtin_lsx_vrotri_h:
4574  case LoongArch::BI__builtin_lsx_vsrlri_h:
4575  return BuiltinConstantArgRange(TheCall, 1, 0, 15);
4576  case LoongArch::BI__builtin_lsx_vssrarni_b_h:
4577  case LoongArch::BI__builtin_lsx_vssrarni_bu_h:
4578  case LoongArch::BI__builtin_lsx_vssrani_b_h:
4579  case LoongArch::BI__builtin_lsx_vssrani_bu_h:
4580  case LoongArch::BI__builtin_lsx_vsrarni_b_h:
4581  case LoongArch::BI__builtin_lsx_vsrlni_b_h:
4582  case LoongArch::BI__builtin_lsx_vsrlrni_b_h:
4583  case LoongArch::BI__builtin_lsx_vssrlni_b_h:
4584  case LoongArch::BI__builtin_lsx_vssrlni_bu_h:
4585  case LoongArch::BI__builtin_lsx_vssrlrni_b_h:
4586  case LoongArch::BI__builtin_lsx_vssrlrni_bu_h:
4587  case LoongArch::BI__builtin_lsx_vsrani_b_h:
4588  return BuiltinConstantArgRange(TheCall, 2, 0, 15);
4589  case LoongArch::BI__builtin_lsx_vslei_bu:
4590  case LoongArch::BI__builtin_lsx_vslei_hu:
4591  case LoongArch::BI__builtin_lsx_vslei_wu:
4592  case LoongArch::BI__builtin_lsx_vslei_du:
4593  case LoongArch::BI__builtin_lsx_vslti_bu:
4594  case LoongArch::BI__builtin_lsx_vslti_hu:
4595  case LoongArch::BI__builtin_lsx_vslti_wu:
4596  case LoongArch::BI__builtin_lsx_vslti_du:
4597  case LoongArch::BI__builtin_lsx_vmaxi_bu:
4598  case LoongArch::BI__builtin_lsx_vmaxi_hu:
4599  case LoongArch::BI__builtin_lsx_vmaxi_wu:
4600  case LoongArch::BI__builtin_lsx_vmaxi_du:
4601  case LoongArch::BI__builtin_lsx_vmini_bu:
4602  case LoongArch::BI__builtin_lsx_vmini_hu:
4603  case LoongArch::BI__builtin_lsx_vmini_wu:
4604  case LoongArch::BI__builtin_lsx_vmini_du:
4605  case LoongArch::BI__builtin_lsx_vaddi_bu:
4606  case LoongArch::BI__builtin_lsx_vaddi_hu:
4607  case LoongArch::BI__builtin_lsx_vaddi_wu:
4608  case LoongArch::BI__builtin_lsx_vaddi_du:
4609  case LoongArch::BI__builtin_lsx_vbitclri_w:
4610  case LoongArch::BI__builtin_lsx_vbitrevi_w:
4611  case LoongArch::BI__builtin_lsx_vbitseti_w:
4612  case LoongArch::BI__builtin_lsx_vsat_w:
4613  case LoongArch::BI__builtin_lsx_vsat_wu:
4614  case LoongArch::BI__builtin_lsx_vslli_w:
4615  case LoongArch::BI__builtin_lsx_vsrai_w:
4616  case LoongArch::BI__builtin_lsx_vsrari_w:
4617  case LoongArch::BI__builtin_lsx_vsrli_w:
4618  case LoongArch::BI__builtin_lsx_vsllwil_d_w:
4619  case LoongArch::BI__builtin_lsx_vsllwil_du_wu:
4620  case LoongArch::BI__builtin_lsx_vsrlri_w:
4621  case LoongArch::BI__builtin_lsx_vrotri_w:
4622  case LoongArch::BI__builtin_lsx_vsubi_bu:
4623  case LoongArch::BI__builtin_lsx_vsubi_hu:
4624  case LoongArch::BI__builtin_lsx_vbsrl_v:
4625  case LoongArch::BI__builtin_lsx_vbsll_v:
4626  case LoongArch::BI__builtin_lsx_vsubi_wu:
4627  case LoongArch::BI__builtin_lsx_vsubi_du:
4628  return BuiltinConstantArgRange(TheCall, 1, 0, 31);
4629  case LoongArch::BI__builtin_lsx_vssrarni_h_w:
4630  case LoongArch::BI__builtin_lsx_vssrarni_hu_w:
4631  case LoongArch::BI__builtin_lsx_vssrani_h_w:
4632  case LoongArch::BI__builtin_lsx_vssrani_hu_w:
4633  case LoongArch::BI__builtin_lsx_vsrarni_h_w:
4634  case LoongArch::BI__builtin_lsx_vsrani_h_w:
4635  case LoongArch::BI__builtin_lsx_vfrstpi_b:
4636  case LoongArch::BI__builtin_lsx_vfrstpi_h:
4637  case LoongArch::BI__builtin_lsx_vsrlni_h_w:
4638  case LoongArch::BI__builtin_lsx_vsrlrni_h_w:
4639  case LoongArch::BI__builtin_lsx_vssrlni_h_w:
4640  case LoongArch::BI__builtin_lsx_vssrlni_hu_w:
4641  case LoongArch::BI__builtin_lsx_vssrlrni_h_w:
4642  case LoongArch::BI__builtin_lsx_vssrlrni_hu_w:
4643  return BuiltinConstantArgRange(TheCall, 2, 0, 31);
4644  case LoongArch::BI__builtin_lsx_vbitclri_d:
4645  case LoongArch::BI__builtin_lsx_vbitrevi_d:
4646  case LoongArch::BI__builtin_lsx_vbitseti_d:
4647  case LoongArch::BI__builtin_lsx_vsat_d:
4648  case LoongArch::BI__builtin_lsx_vsat_du:
4649  case LoongArch::BI__builtin_lsx_vslli_d:
4650  case LoongArch::BI__builtin_lsx_vsrai_d:
4651  case LoongArch::BI__builtin_lsx_vsrli_d:
4652  case LoongArch::BI__builtin_lsx_vsrari_d:
4653  case LoongArch::BI__builtin_lsx_vrotri_d:
4654  case LoongArch::BI__builtin_lsx_vsrlri_d:
4655  return BuiltinConstantArgRange(TheCall, 1, 0, 63);
4656  case LoongArch::BI__builtin_lsx_vssrarni_w_d:
4657  case LoongArch::BI__builtin_lsx_vssrarni_wu_d:
4658  case LoongArch::BI__builtin_lsx_vssrani_w_d:
4659  case LoongArch::BI__builtin_lsx_vssrani_wu_d:
4660  case LoongArch::BI__builtin_lsx_vsrarni_w_d:
4661  case LoongArch::BI__builtin_lsx_vsrlni_w_d:
4662  case LoongArch::BI__builtin_lsx_vsrlrni_w_d:
4663  case LoongArch::BI__builtin_lsx_vssrlni_w_d:
4664  case LoongArch::BI__builtin_lsx_vssrlni_wu_d:
4665  case LoongArch::BI__builtin_lsx_vssrlrni_w_d:
4666  case LoongArch::BI__builtin_lsx_vssrlrni_wu_d:
4667  case LoongArch::BI__builtin_lsx_vsrani_w_d:
4668  return BuiltinConstantArgRange(TheCall, 2, 0, 63);
4669  case LoongArch::BI__builtin_lsx_vssrarni_d_q:
4670  case LoongArch::BI__builtin_lsx_vssrarni_du_q:
4671  case LoongArch::BI__builtin_lsx_vssrani_d_q:
4672  case LoongArch::BI__builtin_lsx_vssrani_du_q:
4673  case LoongArch::BI__builtin_lsx_vsrarni_d_q:
4674  case LoongArch::BI__builtin_lsx_vssrlni_d_q:
4675  case LoongArch::BI__builtin_lsx_vssrlni_du_q:
4676  case LoongArch::BI__builtin_lsx_vssrlrni_d_q:
4677  case LoongArch::BI__builtin_lsx_vssrlrni_du_q:
4678  case LoongArch::BI__builtin_lsx_vsrani_d_q:
4679  case LoongArch::BI__builtin_lsx_vsrlrni_d_q:
4680  case LoongArch::BI__builtin_lsx_vsrlni_d_q:
4681  return BuiltinConstantArgRange(TheCall, 2, 0, 127);
4682  case LoongArch::BI__builtin_lsx_vseqi_b:
4683  case LoongArch::BI__builtin_lsx_vseqi_h:
4684  case LoongArch::BI__builtin_lsx_vseqi_w:
4685  case LoongArch::BI__builtin_lsx_vseqi_d:
4686  case LoongArch::BI__builtin_lsx_vslti_b:
4687  case LoongArch::BI__builtin_lsx_vslti_h:
4688  case LoongArch::BI__builtin_lsx_vslti_w:
4689  case LoongArch::BI__builtin_lsx_vslti_d:
4690  case LoongArch::BI__builtin_lsx_vslei_b:
4691  case LoongArch::BI__builtin_lsx_vslei_h:
4692  case LoongArch::BI__builtin_lsx_vslei_w:
4693  case LoongArch::BI__builtin_lsx_vslei_d:
4694  case LoongArch::BI__builtin_lsx_vmaxi_b:
4695  case LoongArch::BI__builtin_lsx_vmaxi_h:
4696  case LoongArch::BI__builtin_lsx_vmaxi_w:
4697  case LoongArch::BI__builtin_lsx_vmaxi_d:
4698  case LoongArch::BI__builtin_lsx_vmini_b:
4699  case LoongArch::BI__builtin_lsx_vmini_h:
4700  case LoongArch::BI__builtin_lsx_vmini_w:
4701  case LoongArch::BI__builtin_lsx_vmini_d:
4702  return BuiltinConstantArgRange(TheCall, 1, -16, 15);
4703  case LoongArch::BI__builtin_lsx_vandi_b:
4704  case LoongArch::BI__builtin_lsx_vnori_b:
4705  case LoongArch::BI__builtin_lsx_vori_b:
4706  case LoongArch::BI__builtin_lsx_vshuf4i_b:
4707  case LoongArch::BI__builtin_lsx_vshuf4i_h:
4708  case LoongArch::BI__builtin_lsx_vshuf4i_w:
4709  case LoongArch::BI__builtin_lsx_vxori_b:
4710  return BuiltinConstantArgRange(TheCall, 1, 0, 255);
4711  case LoongArch::BI__builtin_lsx_vbitseli_b:
4712  case LoongArch::BI__builtin_lsx_vshuf4i_d:
4713  case LoongArch::BI__builtin_lsx_vextrins_b:
4714  case LoongArch::BI__builtin_lsx_vextrins_h:
4715  case LoongArch::BI__builtin_lsx_vextrins_w:
4716  case LoongArch::BI__builtin_lsx_vextrins_d:
4717  case LoongArch::BI__builtin_lsx_vpermi_w:
4718  return BuiltinConstantArgRange(TheCall, 2, 0, 255);
4719  case LoongArch::BI__builtin_lsx_vpickve2gr_b:
4720  case LoongArch::BI__builtin_lsx_vpickve2gr_bu:
4721  case LoongArch::BI__builtin_lsx_vreplvei_b:
4722  return BuiltinConstantArgRange(TheCall, 1, 0, 15);
4723  case LoongArch::BI__builtin_lsx_vinsgr2vr_b:
4724  return BuiltinConstantArgRange(TheCall, 2, 0, 15);
4725  case LoongArch::BI__builtin_lsx_vpickve2gr_h:
4726  case LoongArch::BI__builtin_lsx_vpickve2gr_hu:
4727  case LoongArch::BI__builtin_lsx_vreplvei_h:
4728  return BuiltinConstantArgRange(TheCall, 1, 0, 7);
4729  case LoongArch::BI__builtin_lsx_vinsgr2vr_h:
4730  return BuiltinConstantArgRange(TheCall, 2, 0, 7);
4731  case LoongArch::BI__builtin_lsx_vpickve2gr_w:
4732  case LoongArch::BI__builtin_lsx_vpickve2gr_wu:
4733  case LoongArch::BI__builtin_lsx_vreplvei_w:
4734  return BuiltinConstantArgRange(TheCall, 1, 0, 3);
4735  case LoongArch::BI__builtin_lsx_vinsgr2vr_w:
4736  return BuiltinConstantArgRange(TheCall, 2, 0, 3);
4737  case LoongArch::BI__builtin_lsx_vpickve2gr_d:
4738  case LoongArch::BI__builtin_lsx_vpickve2gr_du:
4739  case LoongArch::BI__builtin_lsx_vreplvei_d:
4740  return BuiltinConstantArgRange(TheCall, 1, 0, 1);
4741  case LoongArch::BI__builtin_lsx_vinsgr2vr_d:
4742  return BuiltinConstantArgRange(TheCall, 2, 0, 1);
4743  case LoongArch::BI__builtin_lsx_vstelm_b:
4744  return BuiltinConstantArgRange(TheCall, 2, -128, 127) ||
4745  BuiltinConstantArgRange(TheCall, 3, 0, 15);
4746  case LoongArch::BI__builtin_lsx_vstelm_h:
4747  return BuiltinConstantArgRange(TheCall, 2, -256, 254) ||
4748  BuiltinConstantArgRange(TheCall, 3, 0, 7);
4749  case LoongArch::BI__builtin_lsx_vstelm_w:
4750  return BuiltinConstantArgRange(TheCall, 2, -512, 508) ||
4751  BuiltinConstantArgRange(TheCall, 3, 0, 3);
4752  case LoongArch::BI__builtin_lsx_vstelm_d:
4753  return BuiltinConstantArgRange(TheCall, 2, -1024, 1016) ||
4754  BuiltinConstantArgRange(TheCall, 3, 0, 1);
4755  case LoongArch::BI__builtin_lsx_vldrepl_b:
4756  case LoongArch::BI__builtin_lsx_vld:
4757  return BuiltinConstantArgRange(TheCall, 1, -2048, 2047);
4758  case LoongArch::BI__builtin_lsx_vldrepl_h:
4759  return BuiltinConstantArgRange(TheCall, 1, -2048, 2046);
4760  case LoongArch::BI__builtin_lsx_vldrepl_w:
4761  return BuiltinConstantArgRange(TheCall, 1, -2048, 2044);
4762  case LoongArch::BI__builtin_lsx_vldrepl_d:
4763  return BuiltinConstantArgRange(TheCall, 1, -2048, 2040);
4764  case LoongArch::BI__builtin_lsx_vst:
4765  return BuiltinConstantArgRange(TheCall, 2, -2048, 2047);
4766  case LoongArch::BI__builtin_lsx_vldi:
4767  return BuiltinConstantArgRange(TheCall, 0, -4096, 4095);
4768  case LoongArch::BI__builtin_lsx_vrepli_b:
4769  case LoongArch::BI__builtin_lsx_vrepli_h:
4770  case LoongArch::BI__builtin_lsx_vrepli_w:
4771  case LoongArch::BI__builtin_lsx_vrepli_d:
4772  return BuiltinConstantArgRange(TheCall, 0, -512, 511);
4773 
4774  // LASX intrinsics.
4775  case LoongArch::BI__builtin_lasx_xvbitclri_b:
4776  case LoongArch::BI__builtin_lasx_xvbitrevi_b:
4777  case LoongArch::BI__builtin_lasx_xvbitseti_b:
4778  case LoongArch::BI__builtin_lasx_xvsat_b:
4779  case LoongArch::BI__builtin_lasx_xvsat_bu:
4780  case LoongArch::BI__builtin_lasx_xvslli_b:
4781  case LoongArch::BI__builtin_lasx_xvsrai_b:
4782  case LoongArch::BI__builtin_lasx_xvsrari_b:
4783  case LoongArch::BI__builtin_lasx_xvsrli_b:
4784  case LoongArch::BI__builtin_lasx_xvsllwil_h_b:
4785  case LoongArch::BI__builtin_lasx_xvsllwil_hu_bu:
4786  case LoongArch::BI__builtin_lasx_xvrotri_b:
4787  case LoongArch::BI__builtin_lasx_xvsrlri_b:
4788  return BuiltinConstantArgRange(TheCall, 1, 0, 7);
4789  case LoongArch::BI__builtin_lasx_xvbitclri_h:
4790  case LoongArch::BI__builtin_lasx_xvbitrevi_h:
4791  case LoongArch::BI__builtin_lasx_xvbitseti_h:
4792  case LoongArch::BI__builtin_lasx_xvsat_h:
4793  case LoongArch::BI__builtin_lasx_xvsat_hu:
4794  case LoongArch::BI__builtin_lasx_xvslli_h:
4795  case LoongArch::BI__builtin_lasx_xvsrai_h:
4796  case LoongArch::BI__builtin_lasx_xvsrari_h:
4797  case LoongArch::BI__builtin_lasx_xvsrli_h:
4798  case LoongArch::BI__builtin_lasx_xvsllwil_w_h:
4799  case LoongArch::BI__builtin_lasx_xvsllwil_wu_hu:
4800  case LoongArch::BI__builtin_lasx_xvrotri_h:
4801  case LoongArch::BI__builtin_lasx_xvsrlri_h:
4802  return BuiltinConstantArgRange(TheCall, 1, 0, 15);
4803  case LoongArch::BI__builtin_lasx_xvssrarni_b_h:
4804  case LoongArch::BI__builtin_lasx_xvssrarni_bu_h:
4805  case LoongArch::BI__builtin_lasx_xvssrani_b_h:
4806  case LoongArch::BI__builtin_lasx_xvssrani_bu_h:
4807  case LoongArch::BI__builtin_lasx_xvsrarni_b_h:
4808  case LoongArch::BI__builtin_lasx_xvsrlni_b_h:
4809  case LoongArch::BI__builtin_lasx_xvsrlrni_b_h:
4810  case LoongArch::BI__builtin_lasx_xvssrlni_b_h:
4811  case LoongArch::BI__builtin_lasx_xvssrlni_bu_h:
4812  case LoongArch::BI__builtin_lasx_xvssrlrni_b_h:
4813  case LoongArch::BI__builtin_lasx_xvssrlrni_bu_h:
4814  case LoongArch::BI__builtin_lasx_xvsrani_b_h:
4815  return BuiltinConstantArgRange(TheCall, 2, 0, 15);
4816  case LoongArch::BI__builtin_lasx_xvslei_bu:
4817  case LoongArch::BI__builtin_lasx_xvslei_hu:
4818  case LoongArch::BI__builtin_lasx_xvslei_wu:
4819  case LoongArch::BI__builtin_lasx_xvslei_du:
4820  case LoongArch::BI__builtin_lasx_xvslti_bu:
4821  case LoongArch::BI__builtin_lasx_xvslti_hu:
4822  case LoongArch::BI__builtin_lasx_xvslti_wu:
4823  case LoongArch::BI__builtin_lasx_xvslti_du:
4824  case LoongArch::BI__builtin_lasx_xvmaxi_bu:
4825  case LoongArch::BI__builtin_lasx_xvmaxi_hu:
4826  case LoongArch::BI__builtin_lasx_xvmaxi_wu:
4827  case LoongArch::BI__builtin_lasx_xvmaxi_du:
4828  case LoongArch::BI__builtin_lasx_xvmini_bu:
4829  case LoongArch::BI__builtin_lasx_xvmini_hu:
4830  case LoongArch::BI__builtin_lasx_xvmini_wu:
4831  case LoongArch::BI__builtin_lasx_xvmini_du:
4832  case LoongArch::BI__builtin_lasx_xvaddi_bu:
4833  case LoongArch::BI__builtin_lasx_xvaddi_hu:
4834  case LoongArch::BI__builtin_lasx_xvaddi_wu:
4835  case LoongArch::BI__builtin_lasx_xvaddi_du:
4836  case LoongArch::BI__builtin_lasx_xvbitclri_w:
4837  case LoongArch::BI__builtin_lasx_xvbitrevi_w:
4838  case LoongArch::BI__builtin_lasx_xvbitseti_w:
4839  case LoongArch::BI__builtin_lasx_xvsat_w:
4840  case LoongArch::BI__builtin_lasx_xvsat_wu:
4841  case LoongArch::BI__builtin_lasx_xvslli_w:
4842  case LoongArch::BI__builtin_lasx_xvsrai_w:
4843  case LoongArch::BI__builtin_lasx_xvsrari_w:
4844  case LoongArch::BI__builtin_lasx_xvsrli_w:
4845  case LoongArch::BI__builtin_lasx_xvsllwil_d_w:
4846  case LoongArch::BI__builtin_lasx_xvsllwil_du_wu:
4847  case LoongArch::BI__builtin_lasx_xvsrlri_w:
4848  case LoongArch::BI__builtin_lasx_xvrotri_w:
4849  case LoongArch::BI__builtin_lasx_xvsubi_bu:
4850  case LoongArch::BI__builtin_lasx_xvsubi_hu:
4851  case LoongArch::BI__builtin_lasx_xvsubi_wu:
4852  case LoongArch::BI__builtin_lasx_xvsubi_du:
4853  case LoongArch::BI__builtin_lasx_xvbsrl_v:
4854  case LoongArch::BI__builtin_lasx_xvbsll_v:
4855  return BuiltinConstantArgRange(TheCall, 1, 0, 31);
4856  case LoongArch::BI__builtin_lasx_xvssrarni_h_w:
4857  case LoongArch::BI__builtin_lasx_xvssrarni_hu_w:
4858  case LoongArch::BI__builtin_lasx_xvssrani_h_w:
4859  case LoongArch::BI__builtin_lasx_xvssrani_hu_w:
4860  case LoongArch::BI__builtin_lasx_xvsrarni_h_w:
4861  case LoongArch::BI__builtin_lasx_xvsrani_h_w:
4862  case LoongArch::BI__builtin_lasx_xvfrstpi_b:
4863  case LoongArch::BI__builtin_lasx_xvfrstpi_h:
4864  case LoongArch::BI__builtin_lasx_xvsrlni_h_w:
4865  case LoongArch::BI__builtin_lasx_xvsrlrni_h_w:
4866  case LoongArch::BI__builtin_lasx_xvssrlni_h_w:
4867  case LoongArch::BI__builtin_lasx_xvssrlni_hu_w:
4868  case LoongArch::BI__builtin_lasx_xvssrlrni_h_w:
4869  case LoongArch::BI__builtin_lasx_xvssrlrni_hu_w:
4870  return BuiltinConstantArgRange(TheCall, 2, 0, 31);
4871  case LoongArch::BI__builtin_lasx_xvbitclri_d:
4872  case LoongArch::BI__builtin_lasx_xvbitrevi_d:
4873  case LoongArch::BI__builtin_lasx_xvbitseti_d:
4874  case LoongArch::BI__builtin_lasx_xvsat_d:
4875  case LoongArch::BI__builtin_lasx_xvsat_du:
4876  case LoongArch::BI__builtin_lasx_xvslli_d:
4877  case LoongArch::BI__builtin_lasx_xvsrai_d:
4878  case LoongArch::BI__builtin_lasx_xvsrli_d:
4879  case LoongArch::BI__builtin_lasx_xvsrari_d:
4880  case LoongArch::BI__builtin_lasx_xvrotri_d:
4881  case LoongArch::BI__builtin_lasx_xvsrlri_d:
4882  return BuiltinConstantArgRange(TheCall, 1, 0, 63);
4883  case LoongArch::BI__builtin_lasx_xvssrarni_w_d:
4884  case LoongArch::BI__builtin_lasx_xvssrarni_wu_d:
4885  case LoongArch::BI__builtin_lasx_xvssrani_w_d:
4886  case LoongArch::BI__builtin_lasx_xvssrani_wu_d:
4887  case LoongArch::BI__builtin_lasx_xvsrarni_w_d:
4888  case LoongArch::BI__builtin_lasx_xvsrlni_w_d:
4889  case LoongArch::BI__builtin_lasx_xvsrlrni_w_d:
4890  case LoongArch::BI__builtin_lasx_xvssrlni_w_d:
4891  case LoongArch::BI__builtin_lasx_xvssrlni_wu_d:
4892  case LoongArch::BI__builtin_lasx_xvssrlrni_w_d:
4893  case LoongArch::BI__builtin_lasx_xvssrlrni_wu_d:
4894  case LoongArch::BI__builtin_lasx_xvsrani_w_d:
4895  return BuiltinConstantArgRange(TheCall, 2, 0, 63);
4896  case LoongArch::BI__builtin_lasx_xvssrarni_d_q:
4897  case LoongArch::BI__builtin_lasx_xvssrarni_du_q:
4898  case LoongArch::BI__builtin_lasx_xvssrani_d_q:
4899  case LoongArch::BI__builtin_lasx_xvssrani_du_q:
4900  case LoongArch::BI__builtin_lasx_xvsrarni_d_q:
4901  case LoongArch::BI__builtin_lasx_xvssrlni_d_q:
4902  case LoongArch::BI__builtin_lasx_xvssrlni_du_q:
4903  case LoongArch::BI__builtin_lasx_xvssrlrni_d_q:
4904  case LoongArch::BI__builtin_lasx_xvssrlrni_du_q:
4905  case LoongArch::BI__builtin_lasx_xvsrani_d_q:
4906  case LoongArch::BI__builtin_lasx_xvsrlni_d_q:
4907  case LoongArch::BI__builtin_lasx_xvsrlrni_d_q:
4908  return BuiltinConstantArgRange(TheCall, 2, 0, 127);
4909  case LoongArch::BI__builtin_lasx_xvseqi_b:
4910  case LoongArch::BI__builtin_lasx_xvseqi_h:
4911  case LoongArch::BI__builtin_lasx_xvseqi_w:
4912  case LoongArch::BI__builtin_lasx_xvseqi_d:
4913  case LoongArch::BI__builtin_lasx_xvslti_b:
4914  case LoongArch::BI__builtin_lasx_xvslti_h:
4915  case LoongArch::BI__builtin_lasx_xvslti_w:
4916  case LoongArch::BI__builtin_lasx_xvslti_d:
4917  case LoongArch::BI__builtin_lasx_xvslei_b:
4918  case LoongArch::BI__builtin_lasx_xvslei_h:
4919  case LoongArch::BI__builtin_lasx_xvslei_w:
4920  case LoongArch::BI__builtin_lasx_xvslei_d:
4921  case LoongArch::BI__builtin_lasx_xvmaxi_b:
4922  case LoongArch::BI__builtin_lasx_xvmaxi_h:
4923  case LoongArch::BI__builtin_lasx_xvmaxi_w:
4924  case LoongArch::BI__builtin_lasx_xvmaxi_d:
4925  case LoongArch::BI__builtin_lasx_xvmini_b:
4926  case LoongArch::BI__builtin_lasx_xvmini_h:
4927  case LoongArch::BI__builtin_lasx_xvmini_w:
4928  case LoongArch::BI__builtin_lasx_xvmini_d:
4929  return BuiltinConstantArgRange(TheCall, 1, -16, 15);
4930  case LoongArch::BI__builtin_lasx_xvandi_b:
4931  case LoongArch::BI__builtin_lasx_xvnori_b:
4932  case LoongArch::BI__builtin_lasx_xvori_b:
4933  case LoongArch::BI__builtin_lasx_xvshuf4i_b:
4934  case LoongArch::BI__builtin_lasx_xvshuf4i_h:
4935  case LoongArch::BI__builtin_lasx_xvshuf4i_w:
4936  case LoongArch::BI__builtin_lasx_xvxori_b:
4937  case LoongArch::BI__builtin_lasx_xvpermi_d:
4938  return BuiltinConstantArgRange(TheCall, 1, 0, 255);
4939  case LoongArch::BI__builtin_lasx_xvbitseli_b:
4940  case LoongArch::BI__builtin_lasx_xvshuf4i_d:
4941  case LoongArch::BI__builtin_lasx_xvextrins_b:
4942  case LoongArch::BI__builtin_lasx_xvextrins_h:
4943  case LoongArch::BI__builtin_lasx_xvextrins_w:
4944  case LoongArch::BI__builtin_lasx_xvextrins_d:
4945  case LoongArch::BI__builtin_lasx_xvpermi_q:
4946  case LoongArch::BI__builtin_lasx_xvpermi_w:
4947  return BuiltinConstantArgRange(TheCall, 2, 0, 255);
4948  case LoongArch::BI__builtin_lasx_xvrepl128vei_b:
4949  return BuiltinConstantArgRange(TheCall, 1, 0, 15);
4950  case LoongArch::BI__builtin_lasx_xvrepl128vei_h:
4951  case LoongArch::BI__builtin_lasx_xvpickve2gr_w:
4952  case LoongArch::BI__builtin_lasx_xvpickve2gr_wu:
4953  case LoongArch::BI__builtin_lasx_xvpickve_w_f:
4954  case LoongArch::BI__builtin_lasx_xvpickve_w:
4955  return BuiltinConstantArgRange(TheCall, 1, 0, 7);
4956  case LoongArch::BI__builtin_lasx_xvinsgr2vr_w:
4957  case LoongArch::BI__builtin_lasx_xvinsve0_w:
4958  return BuiltinConstantArgRange(TheCall, 2, 0, 7);
4959  case LoongArch::BI__builtin_lasx_xvrepl128vei_w:
4960  case LoongArch::BI__builtin_lasx_xvpickve2gr_d:
4961  case LoongArch::BI__builtin_lasx_xvpickve2gr_du:
4962  case LoongArch::BI__builtin_lasx_xvpickve_d_f:
4963  case LoongArch::BI__builtin_lasx_xvpickve_d:
4964  return BuiltinConstantArgRange(TheCall, 1, 0, 3);
4965  case LoongArch::BI__builtin_lasx_xvinsve0_d:
4966  case LoongArch::BI__builtin_lasx_xvinsgr2vr_d:
4967  return BuiltinConstantArgRange(TheCall, 2, 0, 3);
4968  case LoongArch::BI__builtin_lasx_xvstelm_b:
4969  return BuiltinConstantArgRange(TheCall, 2, -128, 127) ||
4970  BuiltinConstantArgRange(TheCall, 3, 0, 31);
4971  case LoongArch::BI__builtin_lasx_xvstelm_h:
4972  return BuiltinConstantArgRange(TheCall, 2, -256, 254) ||
4973  BuiltinConstantArgRange(TheCall, 3, 0, 15);
4974  case LoongArch::BI__builtin_lasx_xvstelm_w:
4975  return BuiltinConstantArgRange(TheCall, 2, -512, 508) ||
4976  BuiltinConstantArgRange(TheCall, 3, 0, 7);
4977  case LoongArch::BI__builtin_lasx_xvstelm_d:
4978  return BuiltinConstantArgRange(TheCall, 2, -1024, 1016) ||
4979  BuiltinConstantArgRange(TheCall, 3, 0, 3);
4980  case LoongArch::BI__builtin_lasx_xvrepl128vei_d:
4981  return BuiltinConstantArgRange(TheCall, 1, 0, 1);
4982  case LoongArch::BI__builtin_lasx_xvldrepl_b:
4983  case LoongArch::BI__builtin_lasx_xvld:
4984  return BuiltinConstantArgRange(TheCall, 1, -2048, 2047);
4985  case LoongArch::BI__builtin_lasx_xvldrepl_h:
4986  return BuiltinConstantArgRange(TheCall, 1, -2048, 2046);
4987  case LoongArch::BI__builtin_lasx_xvldrepl_w:
4988  return BuiltinConstantArgRange(TheCall, 1, -2048, 2044);
4989  case LoongArch::BI__builtin_lasx_xvldrepl_d:
4990  return BuiltinConstantArgRange(TheCall, 1, -2048, 2040);
4991  case LoongArch::BI__builtin_lasx_xvst:
4992  return BuiltinConstantArgRange(TheCall, 2, -2048, 2047);
4993  case LoongArch::BI__builtin_lasx_xvldi:
4994  return BuiltinConstantArgRange(TheCall, 0, -4096, 4095);
4995  case LoongArch::BI__builtin_lasx_xvrepli_b:
4996  case LoongArch::BI__builtin_lasx_xvrepli_h:
4997  case LoongArch::BI__builtin_lasx_xvrepli_w:
4998  case LoongArch::BI__builtin_lasx_xvrepli_d:
4999  return BuiltinConstantArgRange(TheCall, 0, -512, 511);
5000  }
5001  return false;
5002 }
5003 
5004 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
5005  unsigned BuiltinID, CallExpr *TheCall) {
5006  return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
5007  CheckMipsBuiltinArgument(BuiltinID, TheCall);
5008 }
5009 
5010 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
5011  CallExpr *TheCall) {
5012 
5013  if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
5014  BuiltinID <= Mips::BI__builtin_mips_lwx) {
5015  if (!TI.hasFeature("dsp"))
5016  return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
5017  }
5018 
5019  if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
5020  BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
5021  if (!TI.hasFeature("dspr2"))
5022  return Diag(TheCall->getBeginLoc(),
5023  diag::err_mips_builtin_requires_dspr2);
5024  }
5025 
5026  if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
5027  BuiltinID <= Mips::BI__builtin_msa_xori_b) {
5028  if (!TI.hasFeature("msa"))
5029  return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
5030  }
5031 
5032  return false;
5033 }
5034 
5035 // CheckMipsBuiltinArgument - Checks the constant value passed to the
5036 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
5037 // ordering for DSP is unspecified. MSA is ordered by the data format used
5038 // by the underlying instruction i.e., df/m, df/n and then by size.
5039 //
5040 // FIXME: The size tests here should instead be tablegen'd along with the
5041 // definitions from include/clang/Basic/BuiltinsMips.def.
5042 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
5043 // be too.
5044 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
5045  unsigned i = 0, l = 0, u = 0, m = 0;
5046  switch (BuiltinID) {
5047  default: return false;
5048  case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
5049  case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
5050  case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
5051  case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
5052  case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
5053  case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
5054  case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
5055  // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
5056  // df/m field.
5057  // These intrinsics take an unsigned 3 bit immediate.
5058  case Mips::BI__builtin_msa_bclri_b:
5059  case Mips::BI__builtin_msa_bnegi_b:
5060  case Mips::BI__builtin_msa_bseti_b:
5061  case Mips::BI__builtin_msa_sat_s_b:
5062  case Mips::BI__builtin_msa_sat_u_b:
5063  case Mips::BI__builtin_msa_slli_b:
5064  case Mips::BI__builtin_msa_srai_b:
5065  case Mips::BI__builtin_msa_srari_b:
5066  case Mips::BI__builtin_msa_srli_b:
5067  case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
5068  case Mips::BI__builtin_msa_binsli_b:
5069  case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
5070  // These intrinsics take an unsigned 4 bit immediate.
5071  case Mips::BI__builtin_msa_bclri_h:
5072  case Mips::BI__builtin_msa_bnegi_h:
5073  case Mips::BI__builtin_msa_bseti_h:
5074  case Mips::BI__builtin_msa_sat_s_h:
5075  case Mips::BI__builtin_msa_sat_u_h:
5076  case Mips::BI__builtin_msa_slli_h:
5077  case Mips::BI__builtin_msa_srai_h:
5078  case Mips::BI__builtin_msa_srari_h:
5079  case Mips::BI__builtin_msa_srli_h:
5080  case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
5081  case Mips::BI__builtin_msa_binsli_h:
5082  case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
5083  // These intrinsics take an unsigned 5 bit immediate.
5084  // The first block of intrinsics actually have an unsigned 5 bit field,
5085  // not a df/n field.
5086  case Mips::BI__builtin_msa_cfcmsa:
5087  case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
5088  case Mips::BI__builtin_msa_clei_u_b:
5089  case Mips::BI__builtin_msa_clei_u_h:
5090  case Mips::BI__builtin_msa_clei_u_w:
5091  case Mips::BI__builtin_msa_clei_u_d:
5092  case Mips::BI__builtin_msa_clti_u_b:
5093  case Mips::BI__builtin_msa_clti_u_h:
5094  case Mips::BI__builtin_msa_clti_u_w:
5095  case Mips::BI__builtin_msa_clti_u_d:
5096  case Mips::BI__builtin_msa_maxi_u_b:
5097  case Mips::BI__builtin_msa_maxi_u_h:
5098  case Mips::BI__builtin_msa_maxi_u_w:
5099  case Mips::BI__builtin_msa_maxi_u_d:
5100  case Mips::BI__builtin_msa_mini_u_b:
5101  case Mips::BI__builtin_msa_mini_u_h:
5102  case Mips::BI__builtin_msa_mini_u_w:
5103  case Mips::BI__builtin_msa_mini_u_d:
5104  case Mips::BI__builtin_msa_addvi_b:
5105  case Mips::BI__builtin_msa_addvi_h:
5106  case Mips::BI__builtin_msa_addvi_w:
5107  case Mips::BI__builtin_msa_addvi_d:
5108  case Mips::BI__builtin_msa_bclri_w:
5109  case Mips::BI__builtin_msa_bnegi_w:
5110  case Mips::BI__builtin_msa_bseti_w:
5111  case Mips::BI__builtin_msa_sat_s_w:
5112  case Mips::BI__builtin_msa_sat_u_w:
5113  case Mips::BI__builtin_msa_slli_w:
5114  case Mips::BI__builtin_msa_srai_w:
5115  case Mips::BI__builtin_msa_srari_w:
5116  case Mips::BI__builtin_msa_srli_w:
5117  case Mips::BI__builtin_msa_srlri_w:
5118  case Mips::BI__builtin_msa_subvi_b:
5119  case Mips::BI__builtin_msa_subvi_h:
5120  case Mips::BI__builtin_msa_subvi_w:
5121  case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
5122  case Mips::BI__builtin_msa_binsli_w:
5123  case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
5124  // These intrinsics take an unsigned 6 bit immediate.
5125  case Mips::BI__builtin_msa_bclri_d:
5126  case Mips::BI__builtin_msa_bnegi_d:
5127  case Mips::BI__builtin_msa_bseti_d:
5128  case Mips::BI__builtin_msa_sat_s_d:
5129  case Mips::BI__builtin_msa_sat_u_d:
5130  case Mips::BI__builtin_msa_slli_d:
5131  case Mips::BI__builtin_msa_srai_d:
5132  case Mips::BI__builtin_msa_srari_d:
5133  case Mips::BI__builtin_msa_srli_d:
5134  case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
5135  case Mips::BI__builtin_msa_binsli_d:
5136  case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
5137  // These intrinsics take a signed 5 bit immediate.
5138  case Mips::BI__builtin_msa_ceqi_b:
5139  case Mips::BI__builtin_msa_ceqi_h:
5140  case Mips::BI__builtin_msa_ceqi_w:
5141  case Mips::BI__builtin_msa_ceqi_d:
5142  case Mips::BI__builtin_msa_clti_s_b:
5143  case Mips::BI__builtin_msa_clti_s_h:
5144  case Mips::BI__builtin_msa_clti_s_w:
5145  case Mips::BI__builtin_msa_clti_s_d:
5146  case Mips::BI__builtin_msa_clei_s_b:
5147  case Mips::BI__builtin_msa_clei_s_h:
5148  case Mips::BI__builtin_msa_clei_s_w:
5149  case Mips::BI__builtin_msa_clei_s_d:
5150  case Mips::BI__builtin_msa_maxi_s_b:
5151  case Mips::BI__builtin_msa_maxi_s_h:
5152  case Mips::BI__builtin_msa_maxi_s_w:
5153  case Mips::BI__builtin_msa_maxi_s_d:
5154  case Mips::BI__builtin_msa_mini_s_b:
5155  case Mips::BI__builtin_msa_mini_s_h:
5156  case Mips::BI__builtin_msa_mini_s_w:
5157  case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
5158  // These intrinsics take an unsigned 8 bit immediate.
5159  case Mips::BI__builtin_msa_andi_b:
5160  case Mips::BI__builtin_msa_nori_b:
5161  case Mips::BI__builtin_msa_ori_b:
5162  case Mips::BI__builtin_msa_shf_b:
5163  case Mips::BI__builtin_msa_shf_h:
5164  case Mips::BI__builtin_msa_shf_w:
5165  case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
5166  case Mips::BI__builtin_msa_bseli_b:
5167  case Mips::BI__builtin_msa_bmnzi_b:
5168  case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
5169  // df/n format
5170  // These intrinsics take an unsigned 4 bit immediate.
5171  case Mips::BI__builtin_msa_copy_s_b:
5172  case Mips::BI__builtin_msa_copy_u_b:
5173  case Mips::BI__builtin_msa_insve_b:
5174  case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
5175  case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
5176  // These intrinsics take an unsigned 3 bit immediate.
5177  case Mips::BI__builtin_msa_copy_s_h:
5178  case Mips::BI__builtin_msa_copy_u_h:
5179  case Mips::BI__builtin_msa_insve_h:
5180  case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
5181  case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
5182  // These intrinsics take an unsigned 2 bit immediate.
5183  case Mips::BI__builtin_msa_copy_s_w:
5184  case Mips::BI__builtin_msa_copy_u_w:
5185  case Mips::BI__builtin_msa_insve_w:
5186  case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
5187  case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
5188  // These intrinsics take an unsigned 1 bit immediate.
5189  case Mips::BI__builtin_msa_copy_s_d:
5190  case Mips::BI__builtin_msa_copy_u_d:
5191  case Mips::BI__builtin_msa_insve_d:
5192  case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
5193  case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
5194  // Memory offsets and immediate loads.
5195  // These intrinsics take a signed 10 bit immediate.
5196  case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
5197  case Mips::BI__builtin_msa_ldi_h:
5198  case Mips::BI__builtin_msa_ldi_w:
5199  case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
5200  case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
5201  case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
5202  case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
5203  case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
5204  case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
5205  case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
5206  case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
5207  case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
5208  case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
5209  case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
5210  case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
5211  case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
5212  }
5213 
5214  if (!m)
5215  return BuiltinConstantArgRange(TheCall, i, l, u);
5216 
5217  return BuiltinConstantArgRange(TheCall, i, l, u) ||
5218  BuiltinConstantArgMultiple(TheCall, i, m);
5219 }
5220 
5221 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
5222 /// advancing the pointer over the consumed characters. The decoded type is
5223 /// returned. If the decoded type represents a constant integer with a
5224 /// constraint on its value then Mask is set to that value. The type descriptors
5225 /// used in Str are specific to PPC MMA builtins and are documented in the file
5226 /// defining the PPC builtins.
5227 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
5228  unsigned &Mask) {
5229  bool RequireICE = false;
5231  switch (*Str++) {
5232  case 'V':
5233  return Context.getVectorType(Context.UnsignedCharTy, 16,
5235  case 'i': {
5236  char *End;
5237  unsigned size = strtoul(Str, &End, 10);
5238  assert(End != Str && "Missing constant parameter constraint");
5239  Str = End;
5240  Mask = size;
5241  return Context.IntTy;
5242  }
5243  case 'W': {
5244  char *End;
5245  unsigned size = strtoul(Str, &End, 10);
5246  assert(End != Str && "Missing PowerPC MMA type size");
5247  Str = End;
5248  QualType Type;
5249  switch (size) {
5250  #define PPC_VECTOR_TYPE(typeName, Id, size) \
5251  case size: Type = Context.Id##Ty; break;
5252  #include "clang/Basic/PPCTypes.def"
5253  default: llvm_unreachable("Invalid PowerPC MMA vector type");
5254  }
5255  bool CheckVectorArgs = false;
5256  while (!CheckVectorArgs) {
5257  switch (*Str++) {
5258  case '*':
5259  Type = Context.getPointerType(Type);
5260  break;
5261  case 'C':
5262  Type = Type.withConst();
5263  break;
5264  default:
5265  CheckVectorArgs = true;
5266  --Str;
5267  break;
5268  }
5269  }
5270  return Type;
5271  }
5272  default:
5273  return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
5274  }
5275 }
5276 
5277 static bool isPPC_64Builtin(unsigned BuiltinID) {
5278  // These builtins only work on PPC 64bit targets.
5279  switch (BuiltinID) {
5280  case PPC::BI__builtin_divde:
5281  case PPC::BI__builtin_divdeu:
5282  case PPC::BI__builtin_bpermd:
5283  case PPC::BI__builtin_pdepd:
5284  case PPC::BI__builtin_pextd:
5285  case PPC::BI__builtin_ppc_ldarx:
5286  case PPC::BI__builtin_ppc_stdcx:
5287  case PPC::BI__builtin_ppc_tdw:
5288  case PPC::BI__builtin_ppc_trapd:
5289  case PPC::BI__builtin_ppc_cmpeqb:
5290  case PPC::BI__builtin_ppc_setb:
5291  case PPC::BI__builtin_ppc_mulhd:
5292  case PPC::BI__builtin_ppc_mulhdu:
5293  case PPC::BI__builtin_ppc_maddhd:
5294  case PPC::BI__builtin_ppc_maddhdu:
5295  case PPC::BI__builtin_ppc_maddld:
5296  case PPC::BI__builtin_ppc_load8r:
5297  case PPC::BI__builtin_ppc_store8r:
5298  case PPC::BI__builtin_ppc_insert_exp:
5299  case PPC::BI__builtin_ppc_extract_sig:
5300  case PPC::BI__builtin_ppc_addex:
5301  case PPC::BI__builtin_darn:
5302  case PPC::BI__builtin_darn_raw:
5303  case PPC::BI__builtin_ppc_compare_and_swaplp:
5304  case PPC::BI__builtin_ppc_fetch_and_addlp:
5305  case PPC::BI__builtin_ppc_fetch_and_andlp:
5306  case PPC::BI__builtin_ppc_fetch_and_orlp:
5307  case PPC::BI__builtin_ppc_fetch_and_swaplp:
5308  return true;
5309  }
5310  return false;
5311 }
5312 
5313 /// Returns true if the argument consists of one contiguous run of 1s with any
5314 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
5315 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
5316 /// since all 1s are not contiguous.
5317 bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
5318  llvm::APSInt Result;
5319  // We can't check the value of a dependent argument.
5320  Expr *Arg = TheCall->getArg(ArgNum);
5321  if (Arg->isTypeDependent() || Arg->isValueDependent())
5322  return false;
5323 
5324  // Check constant-ness first.
5325  if (BuiltinConstantArg(TheCall, ArgNum, Result))
5326  return true;
5327 
5328  // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
5329  if (Result.isShiftedMask() || (~Result).isShiftedMask())
5330  return false;
5331 
5332  return Diag(TheCall->getBeginLoc(),
5333  diag::err_argument_not_contiguous_bit_field)
5334  << ArgNum << Arg->getSourceRange();
5335 }
5336 
5337 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
5338  CallExpr *TheCall) {
5339  unsigned i = 0, l = 0, u = 0;
5340  bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
5341  llvm::APSInt Result;
5342 
5343  if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
5344  return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
5345  << TheCall->getSourceRange();
5346 
5347  switch (BuiltinID) {
5348  default: return false;
5349  case PPC::BI__builtin_altivec_crypto_vshasigmaw:
5350  case PPC::BI__builtin_altivec_crypto_vshasigmad:
5351  return BuiltinConstantArgRange(TheCall, 1, 0, 1) ||
5352  BuiltinConstantArgRange(TheCall, 2, 0, 15);
5353  case PPC::BI__builtin_altivec_dss:
5354  return BuiltinConstantArgRange(TheCall, 0, 0, 3);
5355  case PPC::BI__builtin_tbegin:
5356  case PPC::BI__builtin_tend:
5357  return BuiltinConstantArgRange(TheCall, 0, 0, 1);
5358  case PPC::BI__builtin_tsr:
5359  return BuiltinConstantArgRange(TheCall, 0, 0, 7);
5360  case PPC::BI__builtin_tabortwc:
5361  case PPC::BI__builtin_tabortdc:
5362  return BuiltinConstantArgRange(TheCall, 0, 0, 31);
5363  case PPC::BI__builtin_tabortwci:
5364  case PPC::BI__builtin_tabortdci:
5365  return BuiltinConstantArgRange(TheCall, 0, 0, 31) ||
5366  BuiltinConstantArgRange(TheCall, 2, 0, 31);
5367  // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05',
5368  // __builtin_(un)pack_longdouble are available only if long double uses IBM
5369  // extended double representation.
5370  case PPC::BI__builtin_unpack_longdouble:
5371  if (BuiltinConstantArgRange(TheCall, 1, 0, 1))
5372  return true;
5373  [[fallthrough]];
5374  case PPC::BI__builtin_pack_longdouble:
5375  if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble())
5376  return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi)
5377  << "ibmlongdouble";
5378  return false;
5379  case PPC::BI__builtin_altivec_dst:
5380  case PPC::BI__builtin_altivec_dstt:
5381  case PPC::BI__builtin_altivec_dstst:
5382  case PPC::BI__builtin_altivec_dststt:
5383  return BuiltinConstantArgRange(TheCall, 2, 0, 3);
5384  case PPC::BI__builtin_vsx_xxpermdi:
5385  case PPC::BI__builtin_vsx_xxsldwi:
5386  return BuiltinVSX(TheCall);
5387  case PPC::BI__builtin_unpack_vector_int128:
5388  return BuiltinConstantArgRange(TheCall, 1, 0, 1);
5389  case PPC::BI__builtin_altivec_vgnb:
5390  return BuiltinConstantArgRange(TheCall, 1, 2, 7);
5391  case PPC::BI__builtin_vsx_xxeval:
5392  return BuiltinConstantArgRange(TheCall, 3, 0, 255);
5393  case PPC::BI__builtin_altivec_vsldbi:
5394  return BuiltinConstantArgRange(TheCall, 2, 0, 7);
5395  case PPC::BI__builtin_altivec_vsrdbi:
5396  return BuiltinConstantArgRange(TheCall, 2, 0, 7);
5397  case PPC::BI__builtin_vsx_xxpermx:
5398  return BuiltinConstantArgRange(TheCall, 3, 0, 7);
5399  case PPC::BI__builtin_ppc_tw:
5400  case PPC::BI__builtin_ppc_tdw:
5401  return BuiltinConstantArgRange(TheCall, 2, 1, 31);
5402  case PPC::BI__builtin_ppc_cmprb:
5403  return BuiltinConstantArgRange(TheCall, 0, 0, 1);
5404  // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
5405  // be a constant that represents a contiguous bit field.
5406  case PPC::BI__builtin_ppc_rlwnm:
5407  return ValueIsRunOfOnes(TheCall, 2);
5408  case PPC::BI__builtin_ppc_rlwimi:
5409  return BuiltinConstantArgRange(TheCall, 2, 0, 31) ||
5410  ValueIsRunOfOnes(TheCall, 3);
5411  case PPC::BI__builtin_ppc_rldimi:
5412  return BuiltinConstantArgRange(TheCall, 2, 0, 63) ||
5413  ValueIsRunOfOnes(TheCall, 3);
5414  case PPC::BI__builtin_ppc_addex: {
5415  if (BuiltinConstantArgRange(TheCall, 2, 0, 3))
5416  return true;
5417  // Output warning for reserved values 1 to 3.
5418  int ArgValue =
5419  TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
5420  if (ArgValue != 0)
5421  Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
5422  << ArgValue;
5423  return false;
5424  }
5425  case PPC::BI__builtin_ppc_mtfsb0:
5426  case PPC::BI__builtin_ppc_mtfsb1:
5427  return BuiltinConstantArgRange(TheCall, 0, 0, 31);
5428  case PPC::BI__builtin_ppc_mtfsf:
5429  return BuiltinConstantArgRange(TheCall, 0, 0, 255);
5430  case PPC::BI__builtin_ppc_mtfsfi:
5431  return BuiltinConstantArgRange(TheCall, 0, 0, 7) ||
5432  BuiltinConstantArgRange(TheCall, 1, 0, 15);
5433  case PPC::BI__builtin_ppc_alignx:
5434  return BuiltinConstantArgPower2(TheCall, 0);
5435  case PPC::BI__builtin_ppc_rdlam:
5436  return ValueIsRunOfOnes(TheCall, 2);
5437  case PPC::BI__builtin_vsx_ldrmb:
5438  case PPC::BI__builtin_vsx_strmb:
5439  return BuiltinConstantArgRange(TheCall, 1, 1, 16);
5440  case PPC::BI__builtin_altivec_vcntmbb:
5441  case PPC::BI__builtin_altivec_vcntmbh:
5442  case PPC::BI__builtin_altivec_vcntmbw:
5443  case PPC::BI__builtin_altivec_vcntmbd:
5444  return BuiltinConstantArgRange(TheCall, 1, 0, 1);
5445  case PPC::BI__builtin_vsx_xxgenpcvbm:
5446  case PPC::BI__builtin_vsx_xxgenpcvhm:
5447  case PPC::BI__builtin_vsx_xxgenpcvwm:
5448  case PPC::BI__builtin_vsx_xxgenpcvdm:
5449  return BuiltinConstantArgRange(TheCall, 1, 0, 3);
5450  case PPC::BI__builtin_ppc_test_data_class: {
5451  // Check if the first argument of the __builtin_ppc_test_data_class call is
5452  // valid. The argument must be 'float' or 'double' or '__float128'.
5453  QualType ArgType = TheCall->getArg(0)->getType();
5454  if (ArgType != QualType(Context.FloatTy) &&
5455  ArgType != QualType(Context.DoubleTy) &&
5456  ArgType != QualType(Context.Float128Ty))
5457  return Diag(TheCall->getBeginLoc(),
5458  diag::err_ppc_invalid_test_data_class_type);
5459  return BuiltinConstantArgRange(TheCall, 1, 0, 127);
5460  }
5461  case PPC::BI__builtin_ppc_maxfe:
5462  case PPC::BI__builtin_ppc_minfe:
5463  case PPC::BI__builtin_ppc_maxfl:
5464  case PPC::BI__builtin_ppc_minfl:
5465  case PPC::BI__builtin_ppc_maxfs:
5466  case PPC::BI__builtin_ppc_minfs: {
5467  if (Context.getTargetInfo().getTriple().isOSAIX() &&
5468  (BuiltinID == PPC::BI__builtin_ppc_maxfe ||
5469  BuiltinID == PPC::BI__builtin_ppc_minfe))
5470  return Diag(TheCall->getBeginLoc(), diag::err_target_unsupported_type)
5471  << "builtin" << true << 128 << QualType(Context.LongDoubleTy)
5472  << false << Context.getTargetInfo().getTriple().str();
5473  // Argument type should be exact.
5474  QualType ArgType = QualType(Context.LongDoubleTy);
5475  if (BuiltinID == PPC::BI__builtin_ppc_maxfl ||
5476  BuiltinID == PPC::BI__builtin_ppc_minfl)
5477  ArgType = QualType(Context.DoubleTy);
5478  else if (BuiltinID == PPC::BI__builtin_ppc_maxfs ||
5479  BuiltinID == PPC::BI__builtin_ppc_minfs)
5480  ArgType = QualType(Context.FloatTy);
5481  for (unsigned I = 0, E = TheCall->getNumArgs(); I < E; ++I)
5482  if (TheCall->getArg(I)->getType() != ArgType)
5483  return Diag(TheCall->getBeginLoc(),
5484  diag::err_typecheck_convert_incompatible)
5485  << TheCall->getArg(I)->getType() << ArgType << 1 << 0 << 0;
5486  return false;
5487  }
5488 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc, Feature) \
5489  case PPC::BI__builtin_##Name: \
5490  return BuiltinPPCMMACall(TheCall, BuiltinID, Types);
5491 #include "clang/Basic/BuiltinsPPC.def"
5492  }
5493  return BuiltinConstantArgRange(TheCall, i, l, u);
5494 }
5495 
5496 // Check if the given type is a non-pointer PPC MMA type. This function is used
5497 // in Sema to prevent invalid uses of restricted PPC MMA types.
5498 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
5499  if (Type->isPointerType() || Type->isArrayType())
5500  return false;
5501 
5502  QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
5503 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
5504  if (false
5505 #include "clang/Basic/PPCTypes.def"
5506  ) {
5507  Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
5508  return true;
5509  }
5510  return false;
5511 }
5512 
5513 // Helper function for CheckHLSLBuiltinFunctionCall
5515  assert(TheCall->getNumArgs() > 1);
5516  ExprResult A = TheCall->getArg(0);
5517 
5518  QualType ArgTyA = A.get()->getType();
5519 
5520  auto *VecTyA = ArgTyA->getAs<VectorType>();
5521  SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5522 
5523  for (unsigned i = 1; i < TheCall->getNumArgs(); ++i) {
5524  ExprResult B = TheCall->getArg(i);
5525  QualType ArgTyB = B.get()->getType();
5526  auto *VecTyB = ArgTyB->getAs<VectorType>();
5527  if (VecTyA == nullptr && VecTyB == nullptr)
5528  return false;
5529 
5530  if (VecTyA && VecTyB) {
5531  bool retValue = false;
5532  if (VecTyA->getElementType() != VecTyB->getElementType()) {
5533  // Note: type promotion is intended to be handeled via the intrinsics
5534  // and not the builtin itself.
5535  S->Diag(TheCall->getBeginLoc(),
5536  diag::err_vec_builtin_incompatible_vector)
5537  << TheCall->getDirectCallee() << /*useAllTerminology*/ true
5538  << SourceRange(A.get()->getBeginLoc(), B.get()->getEndLoc());
5539  retValue = true;
5540  }
5541  if (VecTyA->getNumElements() != VecTyB->getNumElements()) {
5542  // You should only be hitting this case if you are calling the builtin
5543  // directly. HLSL intrinsics should avoid this case via a
5544  // HLSLVectorTruncation.
5545  S->Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5546  << TheCall->getDirectCallee() << /*useAllTerminology*/ true
5547  << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5548  TheCall->getArg(1)->getEndLoc());
5549  retValue = true;
5550  }
5551  return retValue;
5552  }
5553  }
5554 
5555  // Note: if we get here one of the args is a scalar which
5556  // requires a VectorSplat on Arg0 or Arg1
5557  S->Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5558  << TheCall->getDirectCallee() << /*useAllTerminology*/ true
5559  << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5560  TheCall->getArg(1)->getEndLoc());
5561  return true;
5562 }
5563 
5565  Sema *S, CallExpr *TheCall, QualType ExpectedType,
5566  llvm::function_ref<bool(clang::QualType PassedType)> Check) {
5567  for (unsigned i = 0; i < TheCall->getNumArgs(); ++i) {
5568  QualType PassedType = TheCall->getArg(i)->getType();
5569  if (Check(PassedType)) {
5570  if (auto *VecTyA = PassedType->getAs<VectorType>())
5572  ExpectedType, VecTyA->getNumElements(), VecTyA->getVectorKind());
5573  S->Diag(TheCall->getArg(0)->getBeginLoc(),
5574  diag::err_typecheck_convert_incompatible)
5575  << PassedType << ExpectedType << 1 << 0 << 0;
5576  return true;
5577  }
5578  }
5579  return false;
5580 }
5581 
5583  auto checkAllFloatTypes = [](clang::QualType PassedType) -> bool {
5584  return !PassedType->hasFloatingRepresentation();
5585  };
5586  return CheckArgsTypesAreCorrect(S, TheCall, S->Context.FloatTy,
5587  checkAllFloatTypes);
5588 }
5589 
5591  auto checkFloatorHalf = [](clang::QualType PassedType) -> bool {
5592  clang::QualType BaseType =
5593  PassedType->isVectorType()
5594  ? PassedType->getAs<clang::VectorType>()->getElementType()
5595  : PassedType;
5596  return !BaseType->isHalfType() && !BaseType->isFloat32Type();
5597  };
5598  return CheckArgsTypesAreCorrect(S, TheCall, S->Context.FloatTy,
5599  checkFloatorHalf);
5600 }
5601 
5602 bool CheckNoDoubleVectors(Sema *S, CallExpr *TheCall) {
5603  auto checkDoubleVector = [](clang::QualType PassedType) -> bool {
5604  if (const auto *VecTy = PassedType->getAs<VectorType>())
5605  return VecTy->getElementType()->isDoubleType();
5606  return false;
5607  };
5608  return CheckArgsTypesAreCorrect(S, TheCall, S->Context.FloatTy,
5609  checkDoubleVector);
5610 }
5611 
5613  auto checkAllUnsignedTypes = [](clang::QualType PassedType) -> bool {
5614  return !PassedType->hasUnsignedIntegerRepresentation();
5615  };
5616  return CheckArgsTypesAreCorrect(S, TheCall, S->Context.UnsignedIntTy,
5617  checkAllUnsignedTypes);
5618 }
5619 
5621  QualType ReturnType) {
5622  auto *VecTyA = TheCall->getArg(0)->getType()->getAs<VectorType>();
5623  if (VecTyA)
5624  ReturnType = S->Context.getVectorType(ReturnType, VecTyA->getNumElements(),
5626  TheCall->setType(ReturnType);
5627 }
5628 
5629 // Note: returning true in this case results in CheckBuiltinFunctionCall
5630 // returning an ExprError
5631 bool Sema::CheckHLSLBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
5632  switch (BuiltinID) {
5633  case Builtin::BI__builtin_hlsl_elementwise_all:
5634  case Builtin::BI__builtin_hlsl_elementwise_any: {
5635  if (checkArgCount(*this, TheCall, 1))
5636  return true;
5637  break;
5638  }
5639  case Builtin::BI__builtin_hlsl_elementwise_clamp: {
5640  if (checkArgCount(*this, TheCall, 3))
5641  return true;
5642  if (CheckVectorElementCallArgs(this, TheCall))
5643  return true;
5644  if (BuiltinElementwiseTernaryMath(
5645  TheCall, /*CheckForFloatArgs*/
5646  TheCall->getArg(0)->getType()->hasFloatingRepresentation()))
5647  return true;
5648  break;
5649  }
5650  case Builtin::BI__builtin_hlsl_dot: {
5651  if (checkArgCount(*this, TheCall, 2))
5652  return true;
5653  if (CheckVectorElementCallArgs(this, TheCall))
5654  return true;
5655  if (BuiltinVectorToScalarMath(TheCall))
5656  return true;
5657  if (CheckNoDoubleVectors(this, TheCall))
5658  return true;
5659  break;
5660  }
5661  case Builtin::BI__builtin_hlsl_elementwise_rcp: {
5662  if (CheckAllArgsHaveFloatRepresentation(this, TheCall))
5663  return true;
5664  if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
5665  return true;
5666  break;
5667  }
5668  case Builtin::BI__builtin_hlsl_elementwise_rsqrt:
5669  case Builtin::BI__builtin_hlsl_elementwise_frac: {
5670  if (CheckFloatOrHalfRepresentations(this, TheCall))
5671  return true;
5672  if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
5673  return true;
5674  break;
5675  }
5676  case Builtin::BI__builtin_hlsl_elementwise_isinf: {
5677  if (CheckFloatOrHalfRepresentations(this, TheCall))
5678  return true;
5679  if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
5680  return true;
5681  SetElementTypeAsReturnType(this, TheCall, this->Context.BoolTy);
5682  break;
5683  }
5684  case Builtin::BI__builtin_hlsl_lerp: {
5685  if (checkArgCount(*this, TheCall, 3))
5686  return true;
5687  if (CheckVectorElementCallArgs(this, TheCall))
5688  return true;
5689  if (BuiltinElementwiseTernaryMath(TheCall))
5690  return true;
5691  if (CheckFloatOrHalfRepresentations(this, TheCall))
5692  return true;
5693  break;
5694  }
5695  case Builtin::BI__builtin_hlsl_mad: {
5696  if (checkArgCount(*this, TheCall, 3))
5697  return true;
5698  if (CheckVectorElementCallArgs(this, TheCall))
5699  return true;
5700  if (BuiltinElementwiseTernaryMath(
5701  TheCall, /*CheckForFloatArgs*/
5702  TheCall->getArg(0)->getType()->hasFloatingRepresentation()))
5703  return true;
5704  break;
5705  }
5706  // Note these are llvm builtins that we want to catch invalid intrinsic
5707  // generation. Normal handling of these builitns will occur elsewhere.
5708  case Builtin::BI__builtin_elementwise_bitreverse: {
5709  if (CheckUnsignedIntRepresentation(this, TheCall))
5710  return true;
5711  break;
5712  }
5713  case Builtin::BI__builtin_elementwise_ceil:
5714  case Builtin::BI__builtin_elementwise_cos:
5715  case Builtin::BI__builtin_elementwise_exp:
5716  case Builtin::BI__builtin_elementwise_exp2:
5717  case Builtin::BI__builtin_elementwise_floor:
5718  case Builtin::BI__builtin_elementwise_log:
5719  case Builtin::BI__builtin_elementwise_log2:
5720  case Builtin::BI__builtin_elementwise_log10:
5721  case Builtin::BI__builtin_elementwise_pow:
5722  case Builtin::BI__builtin_elementwise_roundeven:
5723  case Builtin::BI__builtin_elementwise_sin:
5724  case Builtin::BI__builtin_elementwise_sqrt:
5725  case Builtin::BI__builtin_elementwise_trunc: {
5726  if (CheckFloatOrHalfRepresentations(this, TheCall))
5727  return true;
5728  break;
5729  }
5730  }
5731  return false;
5732 }
5733 
5734 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
5735  CallExpr *TheCall) {
5736  // position of memory order and scope arguments in the builtin
5737  unsigned OrderIndex, ScopeIndex;
5738  switch (BuiltinID) {
5739  case AMDGPU::BI__builtin_amdgcn_get_fpenv:
5740  case AMDGPU::BI__builtin_amdgcn_set_fpenv:
5741  return false;
5742  case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
5743  case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
5744  case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
5745  case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
5746  OrderIndex = 2;
5747  ScopeIndex = 3;
5748  break;
5749  case AMDGPU::BI__builtin_amdgcn_fence:
5750  OrderIndex = 0;
5751  ScopeIndex = 1;
5752  break;
5753  default:
5754  return false;
5755  }
5756 
5757  ExprResult Arg = TheCall->getArg(OrderIndex);
5758  auto ArgExpr = Arg.get();
5759  Expr::EvalResult ArgResult;
5760 
5761  if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
5762  return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
5763  << ArgExpr->getType();
5764  auto Ord = ArgResult.Val.getInt().getZExtValue();
5765 
5766  // Check validity of memory ordering as per C11 / C++11's memody model.
5767  // Only fence needs check. Atomic dec/inc allow all memory orders.
5768  if (!llvm::isValidAtomicOrderingCABI(Ord))
5769  return Diag(ArgExpr->getBeginLoc(),
5770  diag::warn_atomic_op_has_invalid_memory_order)
5771  << 0 << ArgExpr->getSourceRange();
5772  switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
5773  case llvm::AtomicOrderingCABI::relaxed:
5774  case llvm::AtomicOrderingCABI::consume:
5775  if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
5776  return Diag(ArgExpr->getBeginLoc(),
5777  diag::warn_atomic_op_has_invalid_memory_order)
5778  << 0 << ArgExpr->getSourceRange();
5779  break;
5780  case llvm::AtomicOrderingCABI::acquire:
5781  case llvm::AtomicOrderingCABI::release:
5782  case llvm::AtomicOrderingCABI::acq_rel:
5783  case llvm::AtomicOrderingCABI::seq_cst:
5784  break;
5785  }
5786 
5787  Arg = TheCall->getArg(ScopeIndex);
5788  ArgExpr = Arg.get();
5789  Expr::EvalResult ArgResult1;
5790  // Check that sync scope is a constant literal
5791  if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
5792  return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
5793  << ArgExpr->getType();
5794 
5795  return false;
5796 }
5797 
5798 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
5799  llvm::APSInt Result;
5800 
5801  // We can't check the value of a dependent argument.
5802  Expr *Arg = TheCall->getArg(ArgNum);
5803  if (Arg->isTypeDependent() || Arg->isValueDependent())
5804  return false;
5805 
5806  // Check constant-ness first.
5807  if (BuiltinConstantArg(TheCall, ArgNum, Result))
5808  return true;
5809 
5810  int64_t Val = Result.getSExtValue();
5811  if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
5812  return false;
5813 
5814  return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
5815  << Arg->getSourceRange();
5816 }
5817 
5818 static bool CheckInvalidVLENandLMUL(const TargetInfo &TI, CallExpr *TheCall,
5819  Sema &S, QualType Type, int EGW) {
5820  assert((EGW == 128 || EGW == 256) && "EGW can only be 128 or 256 bits");
5821 
5822  // LMUL * VLEN >= EGW
5825  unsigned ElemSize = S.Context.getTypeSize(Info.ElementType);
5826  unsigned MinElemCount = Info.EC.getKnownMinValue();
5827 
5828  unsigned EGS = EGW / ElemSize;
5829  // If EGS is less than or equal to the minimum number of elements, then the
5830  // type is valid.
5831  if (EGS <= MinElemCount)
5832  return false;
5833 
5834  // Otherwise, we need vscale to be at least EGS / MinElemCont.
5835  assert(EGS % MinElemCount == 0);
5836  unsigned VScaleFactor = EGS / MinElemCount;
5837  // Vscale is VLEN/RVVBitsPerBlock.
5838  unsigned MinRequiredVLEN = VScaleFactor * llvm::RISCV::RVVBitsPerBlock;
5839  std::string RequiredExt = "zvl" + std::to_string(MinRequiredVLEN) + "b";
5840  if (!TI.hasFeature(RequiredExt))
5841  return S.Diag(TheCall->getBeginLoc(),
5842  diag::err_riscv_type_requires_extension) << Type << RequiredExt;
5843 
5844  return false;
5845 }
5846 
5847 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
5848  unsigned BuiltinID,
5849  CallExpr *TheCall) {
5850  // vmulh.vv, vmulh.vx, vmulhu.vv, vmulhu.vx, vmulhsu.vv, vmulhsu.vx,
5851  // vsmul.vv, vsmul.vx are not included for EEW=64 in Zve64*.
5852  switch (BuiltinID) {
5853  default:
5854  break;
5855  case RISCVVector::BI__builtin_rvv_vmulhsu_vv:
5856  case RISCVVector::BI__builtin_rvv_vmulhsu_vx:
5857  case RISCVVector::BI__builtin_rvv_vmulhsu_vv_tu:
5858  case RISCVVector::BI__builtin_rvv_vmulhsu_vx_tu:
5859  case RISCVVector::BI__builtin_rvv_vmulhsu_vv_m:
5860  case RISCVVector::BI__builtin_rvv_vmulhsu_vx_m:
5861  case RISCVVector::BI__builtin_rvv_vmulhsu_vv_mu:
5862  case RISCVVector::BI__builtin_rvv_vmulhsu_vx_mu:
5863  case RISCVVector::BI__builtin_rvv_vmulhsu_vv_tum:
5864  case RISCVVector::BI__builtin_rvv_vmulhsu_vx_tum:
5865  case RISCVVector::BI__builtin_rvv_vmulhsu_vv_tumu:
5866  case RISCVVector::BI__builtin_rvv_vmulhsu_vx_tumu:
5867  case RISCVVector::BI__builtin_rvv_vmulhu_vv:
5868  case RISCVVector::BI__builtin_rvv_vmulhu_vx:
5869  case RISCVVector::BI__builtin_rvv_vmulhu_vv_tu:
5870  case RISCVVector::BI__builtin_rvv_vmulhu_vx_tu:
5871  case RISCVVector::BI__builtin_rvv_vmulhu_vv_m:
5872  case RISCVVector::BI__builtin_rvv_vmulhu_vx_m:
5873  case RISCVVector::BI__builtin_rvv_vmulhu_vv_mu:
5874  case RISCVVector::BI__builtin_rvv_vmulhu_vx_mu:
5875  case RISCVVector::BI__builtin_rvv_vmulhu_vv_tum:
5876  case RISCVVector::BI__builtin_rvv_vmulhu_vx_tum:
5877  case RISCVVector::BI__builtin_rvv_vmulhu_vv_tumu:
5878  case RISCVVector::BI__builtin_rvv_vmulhu_vx_tumu:
5879  case RISCVVector::BI__builtin_rvv_vmulh_vv:
5880  case RISCVVector::BI__builtin_rvv_vmulh_vx:
5881  case RISCVVector::BI__builtin_rvv_vmulh_vv_tu:
5882  case RISCVVector::BI__builtin_rvv_vmulh_vx_tu:
5883  case RISCVVector::BI__builtin_rvv_vmulh_vv_m:
5884  case RISCVVector::BI__builtin_rvv_vmulh_vx_m:
5885  case RISCVVector::BI__builtin_rvv_vmulh_vv_mu:
5886  case RISCVVector::BI__builtin_rvv_vmulh_vx_mu:
5887  case RISCVVector::BI__builtin_rvv_vmulh_vv_tum:
5888  case RISCVVector::BI__builtin_rvv_vmulh_vx_tum:
5889  case RISCVVector::BI__builtin_rvv_vmulh_vv_tumu:
5890  case RISCVVector::BI__builtin_rvv_vmulh_vx_tumu:
5891  case RISCVVector::BI__builtin_rvv_vsmul_vv:
5892  case RISCVVector::BI__builtin_rvv_vsmul_vx:
5893  case RISCVVector::BI__builtin_rvv_vsmul_vv_tu:
5894  case RISCVVector::BI__builtin_rvv_vsmul_vx_tu:
5895  case RISCVVector::BI__builtin_rvv_vsmul_vv_m:
5896  case RISCVVector::BI__builtin_rvv_vsmul_vx_m:
5897  case RISCVVector::BI__builtin_rvv_vsmul_vv_mu:
5898  case RISCVVector::BI__builtin_rvv_vsmul_vx_mu:
5899  case RISCVVector::BI__builtin_rvv_vsmul_vv_tum:
5900  case RISCVVector::BI__builtin_rvv_vsmul_vx_tum:
5901  case RISCVVector::BI__builtin_rvv_vsmul_vv_tumu:
5902  case RISCVVector::BI__builtin_rvv_vsmul_vx_tumu: {
5904  TheCall->getType()->castAs<BuiltinType>());
5905 
5906  if (Context.getTypeSize(Info.ElementType) == 64 && !TI.hasFeature("v"))
5907  return Diag(TheCall->getBeginLoc(),
5908  diag::err_riscv_builtin_requires_extension)
5909  << /* IsExtension */ true << TheCall->getSourceRange() << "v";
5910 
5911  break;
5912  }
5913  }
5914 
5915  switch (BuiltinID) {
5916  case RISCVVector::BI__builtin_rvv_vsetvli:
5917  return BuiltinConstantArgRange(TheCall, 1, 0, 3) ||
5918  CheckRISCVLMUL(TheCall, 2);
5919  case RISCVVector::BI__builtin_rvv_vsetvlimax:
5920  return BuiltinConstantArgRange(TheCall, 0, 0, 3) ||
5921  CheckRISCVLMUL(TheCall, 1);
5922  case RISCVVector::BI__builtin_rvv_vget_v: {
5924  Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
5925  TheCall->getType().getCanonicalType().getTypePtr()));
5927  Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
5928  TheCall->getArg(0)->getType().getCanonicalType().getTypePtr()));
5929  unsigned MaxIndex;
5930  if (VecInfo.NumVectors != 1) // vget for tuple type
5931  MaxIndex = VecInfo.NumVectors;
5932  else // vget for non-tuple type
5933  MaxIndex = (VecInfo.EC.getKnownMinValue() * VecInfo.NumVectors) /
5934  (ResVecInfo.EC.getKnownMinValue() * ResVecInfo.NumVectors);
5935  return BuiltinConstantArgRange(TheCall, 1, 0, MaxIndex - 1);
5936  }
5937  case RISCVVector::BI__builtin_rvv_vset_v: {
5939  Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
5940  TheCall->getType().getCanonicalType().getTypePtr()));
5942  Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(
5943  TheCall->getArg(2)->getType().getCanonicalType().getTypePtr()));
5944  unsigned MaxIndex;
5945  if (ResVecInfo.NumVectors != 1) // vset for tuple type
5946  MaxIndex = ResVecInfo.NumVectors;
5947  else // vset fo non-tuple type
5948  MaxIndex = (ResVecInfo.EC.getKnownMinValue() * ResVecInfo.NumVectors) /
5949  (VecInfo.EC.getKnownMinValue() * VecInfo.NumVectors);
5950  return BuiltinConstantArgRange(TheCall, 1, 0, MaxIndex - 1);
5951  }
5952  // Vector Crypto
5953  case RISCVVector::BI__builtin_rvv_vaeskf1_vi_tu:
5954  case RISCVVector::BI__builtin_rvv_vaeskf2_vi_tu:
5955  case RISCVVector::BI__builtin_rvv_vaeskf2_vi:
5956  case RISCVVector::BI__builtin_rvv_vsm4k_vi_tu: {
5957  QualType Op1Type = TheCall->getArg(0)->getType();
5958  QualType Op2Type = TheCall->getArg(1)->getType();
5959  return CheckInvalidVLENandLMUL(TI, TheCall, *this, Op1Type, 128) ||
5960  CheckInvalidVLENandLMUL(TI, TheCall, *this, Op2Type, 128) ||
5961  BuiltinConstantArgRange(TheCall, 2, 0, 31);
5962  }
5963  case RISCVVector::BI__builtin_rvv_vsm3c_vi_tu:
5964  case RISCVVector::BI__builtin_rvv_vsm3c_vi: {
5965  QualType Op1Type = TheCall->getArg(0)->getType();
5966  return CheckInvalidVLENandLMUL(TI, TheCall, *this, Op1Type, 256) ||
5967  BuiltinConstantArgRange(TheCall, 2, 0, 31);
5968  }
5969  case RISCVVector::BI__builtin_rvv_vaeskf1_vi:
5970  case RISCVVector::BI__builtin_rvv_vsm4k_vi: {
5971  QualType Op1Type = TheCall->getArg(0)->getType();
5972  return CheckInvalidVLENandLMUL(TI, TheCall, *this, Op1Type, 128) ||
5973  BuiltinConstantArgRange(TheCall, 1, 0, 31);
5974  }
5975  case RISCVVector::BI__builtin_rvv_vaesdf_vv:
5976  case RISCVVector::BI__builtin_rvv_vaesdf_vs:
5977  case RISCVVector::BI__builtin_rvv_vaesdm_vv:
5978  case RISCVVector::BI__builtin_rvv_vaesdm_vs:
5979  case RISCVVector::BI__builtin_rvv_vaesef_vv:
5980  case RISCVVector::BI__builtin_rvv_vaesef_vs:
5981  case RISCVVector::BI__builtin_rvv_vaesem_vv:
5982  case RISCVVector::BI__builtin_rvv_vaesem_vs:
5983  case RISCVVector::BI__builtin_rvv_vaesz_vs:
5984  case RISCVVector::BI__builtin_rvv_vsm4r_vv:
5985  case RISCVVector::BI__builtin_rvv_vsm4r_vs:
5986  case RISCVVector::BI__builtin_rvv_vaesdf_vv_tu:
5987  case RISCVVector::BI__builtin_rvv_vaesdf_vs_tu:
5988  case RISCVVector::BI__builtin_rvv_vaesdm_vv_tu:
5989  case RISCVVector::BI__builtin_rvv_vaesdm_vs_tu:
5990  case RISCVVector::BI__builtin_rvv_vaesef_vv_tu:
5991  case RISCVVector::BI__builtin_rvv_vaesef_vs_tu:
5992  case RISCVVector::BI__builtin_rvv_vaesem_vv_tu:
5993  case RISCVVector::BI__builtin_rvv_vaesem_vs_tu:
5994  case RISCVVector::BI__builtin_rvv_vaesz_vs_tu:
5995  case RISCVVector::BI__builtin_rvv_vsm4r_vv_tu:
5996  case RISCVVector::BI__builtin_rvv_vsm4r_vs_tu: {
5997  QualType Op1Type = TheCall->getArg(0)->getType();
5998  QualType Op2Type = TheCall->getArg(1)->getType();
5999  return CheckInvalidVLENandLMUL(TI, TheCall, *this, Op1Type, 128) ||
6000  CheckInvalidVLENandLMUL(TI, TheCall, *this, Op2Type, 128);
6001  }
6002  case RISCVVector::BI__builtin_rvv_vsha2ch_vv:
6003  case RISCVVector::BI__builtin_rvv_vsha2cl_vv:
6004  case RISCVVector::BI__builtin_rvv_vsha2ms_vv:
6005  case RISCVVector::BI__builtin_rvv_vsha2ch_vv_tu:
6006  case RISCVVector::BI__builtin_rvv_vsha2cl_vv_tu:
6007  case RISCVVector::BI__builtin_rvv_vsha2ms_vv_tu: {
6008  QualType Op1Type = TheCall->getArg(0)->getType();
6009  QualType Op2Type = TheCall->getArg(1)->getType();
6010  QualType Op3Type = TheCall->getArg(2)->getType();
6012  Context.getBuiltinVectorTypeInfo(Op1Type->castAs<BuiltinType>());
6013  uint64_t ElemSize = Context.getTypeSize(Info.ElementType);
6014  if (ElemSize == 64 && !TI.hasFeature("zvknhb"))
6015  return Diag(TheCall->getBeginLoc(),
6016  diag::err_riscv_builtin_requires_extension)
6017  << /* IsExtension */ true << TheCall->getSourceRange() << "zvknb";
6018 
6019  return CheckInvalidVLENandLMUL(TI, TheCall, *this, Op1Type, ElemSize * 4) ||
6020  CheckInvalidVLENandLMUL(TI, TheCall, *this, Op2Type, ElemSize * 4) ||
6021  CheckInvalidVLENandLMUL(TI, TheCall, *this, Op3Type, ElemSize * 4);
6022  }
6023 
6024  case RISCVVector::BI__builtin_rvv_sf_vc_i_se:
6025  // bit_27_26, bit_24_20, bit_11_7, simm5, sew, log2lmul
6026  return BuiltinConstantArgRange(TheCall, 0, 0, 3) ||
6027  BuiltinConstantArgRange(TheCall, 1, 0, 31) ||
6028  BuiltinConstantArgRange(TheCall, 2, 0, 31) ||
6029  BuiltinConstantArgRange(TheCall, 3, -16, 15) ||
6030  CheckRISCVLMUL(TheCall, 5);
6031  case RISCVVector::BI__builtin_rvv_sf_vc_iv_se:
6032  // bit_27_26, bit_11_7, vs2, simm5
6033  return BuiltinConstantArgRange(TheCall, 0, 0, 3) ||
6034  BuiltinConstantArgRange(TheCall, 1, 0, 31) ||
6035  BuiltinConstantArgRange(TheCall, 3, -16, 15);
6036  case RISCVVector::BI__builtin_rvv_sf_vc_v_i:
6037  case RISCVVector::BI__builtin_rvv_sf_vc_v_i_se:
6038  // bit_27_26, bit_24_20, simm5
6039  return BuiltinConstantArgRange(TheCall, 0, 0, 3) ||
6040  BuiltinConstantArgRange(TheCall, 1, 0, 31) ||
6041  BuiltinConstantArgRange(TheCall, 2, -16, 15);
6042  case RISCVVector::BI__builtin_rvv_sf_vc_v_iv:
6043  case RISCVVector::BI__builtin_rvv_sf_vc_v_iv_se:
6044  // bit_27_26, vs2, simm5
6045  return BuiltinConstantArgRange(TheCall, 0, 0, 3) ||
6046  BuiltinConstantArgRange(TheCall, 2, -16, 15);
6047  case RISCVVector::BI__builtin_rvv_sf_vc_ivv_se:
6048  case RISCVVector::BI__builtin_rvv_sf_vc_ivw_se:
6049  case RISCVVector::BI__builtin_rvv_sf_vc_v_ivv:
6050  case RISCVVector::BI__builtin_rvv_sf_vc_v_ivw:
6051  case RISCVVector::BI__builtin_rvv_sf_vc_v_ivv_se:
6052  case RISCVVector::BI__builtin_rvv_sf_vc_v_ivw_se:
6053  // bit_27_26, vd, vs2, simm5
6054  return BuiltinConstantArgRange(TheCall, 0, 0, 3) ||
6055  BuiltinConstantArgRange(TheCall, 3, -16, 15);
6056  case RISCVVector::BI__builtin_rvv_sf_vc_x_se:
6057  // bit_27_26, bit_24_20, bit_11_7, xs1, sew, log2lmul
6058  return BuiltinConstantArgRange(TheCall, 0, 0, 3) ||
6059  BuiltinConstantArgRange(TheCall, 1, 0, 31) ||
6060  BuiltinConstantArgRange(TheCall, 2, 0, 31) ||
6061  CheckRISCVLMUL(TheCall, 5);
6062  case RISCVVector::BI__builtin_rvv_sf_vc_xv_se:
6063  case RISCVVector::BI__builtin_rvv_sf_vc_vv_se:
6064  // bit_27_26, bit_11_7, vs2, xs1/vs1
6065  case RISCVVector::BI__builtin_rvv_sf_vc_v_x:
6066  case RISCVVector::BI__builtin_rvv_sf_vc_v_x_se:
6067  // bit_27_26, bit_24-20, xs1
6068  return BuiltinConstantArgRange(TheCall, 0, 0, 3) ||
6069  BuiltinConstantArgRange(TheCall, 1, 0, 31);
6070  case RISCVVector::BI__builtin_rvv_sf_vc_vvv_se:
6071  case RISCVVector::BI__builtin_rvv_sf_vc_xvv_se:
6072  case RISCVVector::BI__builtin_rvv_sf_vc_vvw_se:
6073  case RISCVVector::BI__builtin_rvv_sf_vc_xvw_se:
6074  // bit_27_26, vd, vs2, xs1
6075  case RISCVVector::BI__builtin_rvv_sf_vc_v_xv:
6076  case RISCVVector::BI__builtin_rvv_sf_vc_v_vv:
6077  case RISCVVector::BI__builtin_rvv_sf_vc_v_xv_se:
6078  case RISCVVector::BI__builtin_rvv_sf_vc_v_vv_se:
6079  // bit_27_26, vs2, xs1/vs1
6080  case RISCVVector::BI__builtin_rvv_sf_vc_v_xvv:
6081  case RISCVVector::BI__builtin_rvv_sf_vc_v_vvv:
6082  case RISCVVector::BI__builtin_rvv_sf_vc_v_xvw:
6083  case RISCVVector::BI__builtin_rvv_sf_vc_v_vvw:
6084  case RISCVVector::BI__builtin_rvv_sf_vc_v_xvv_se:
6085  case RISCVVector::BI__builtin_rvv_sf_vc_v_vvv_se:
6086  case RISCVVector::BI__builtin_rvv_sf_vc_v_xvw_se:
6087  case RISCVVector::BI__builtin_rvv_sf_vc_v_vvw_se:
6088  // bit_27_26, vd, vs2, xs1/vs1
6089  return BuiltinConstantArgRange(TheCall, 0, 0, 3);
6090  case RISCVVector::BI__builtin_rvv_sf_vc_fv_se:
6091  // bit_26, bit_11_7, vs2, fs1
6092  return BuiltinConstantArgRange(TheCall, 0, 0, 1) ||
6093  BuiltinConstantArgRange(TheCall, 1, 0, 31);
6094  case RISCVVector::BI__builtin_rvv_sf_vc_fvv_se:
6095  case RISCVVector::BI__builtin_rvv_sf_vc_fvw_se:
6096  case RISCVVector::BI__builtin_rvv_sf_vc_v_fvv:
6097  case RISCVVector::BI__builtin_rvv_sf_vc_v_fvw:
6098  case RISCVVector::BI__builtin_rvv_sf_vc_v_fvv_se:
6099  case RISCVVector::BI__builtin_rvv_sf_vc_v_fvw_se:
6100  // bit_26, vd, vs2, fs1
6101  case RISCVVector::BI__builtin_rvv_sf_vc_v_fv:
6102  case RISCVVector::BI__builtin_rvv_sf_vc_v_fv_se:
6103  // bit_26, vs2, fs1
6104  return BuiltinConstantArgRange(TheCall, 0, 0, 1);
6105  // Check if byteselect is in [0, 3]
6106  case RISCV::BI__builtin_riscv_aes32dsi:
6107  case RISCV::BI__builtin_riscv_aes32dsmi:
6108  case RISCV::BI__builtin_riscv_aes32esi:
6109  case RISCV::BI__builtin_riscv_aes32esmi:
6110  case RISCV::BI__builtin_riscv_sm4ks:
6111  case RISCV::BI__builtin_riscv_sm4ed:
6112  return BuiltinConstantArgRange(TheCall, 2, 0, 3);
6113  // Check if rnum is in [0, 10]
6114  case RISCV::BI__builtin_riscv_aes64ks1i:
6115  return BuiltinConstantArgRange(TheCall, 1, 0, 10);
6116  // Check if value range for vxrm is in [0, 3]
6117  case RISCVVector::BI__builtin_rvv_vaaddu_vv:
6118  case RISCVVector::BI__builtin_rvv_vaaddu_vx:
6119  case RISCVVector::BI__builtin_rvv_vaadd_vv:
6120  case RISCVVector::BI__builtin_rvv_vaadd_vx:
6121  case RISCVVector::BI__builtin_rvv_vasubu_vv:
6122  case RISCVVector::BI__builtin_rvv_vasubu_vx:
6123  case RISCVVector::BI__builtin_rvv_vasub_vv:
6124  case RISCVVector::BI__builtin_rvv_vasub_vx:
6125  case RISCVVector::BI__builtin_rvv_vsmul_vv:
6126  case RISCVVector::BI__builtin_rvv_vsmul_vx:
6127  case RISCVVector::BI__builtin_rvv_vssra_vv:
6128  case RISCVVector::BI__builtin_rvv_vssra_vx:
6129  case RISCVVector::BI__builtin_rvv_vssrl_vv:
6130  case RISCVVector::BI__builtin_rvv_vssrl_vx:
6131  case RISCVVector::BI__builtin_rvv_vnclip_wv:
6132  case RISCVVector::BI__builtin_rvv_vnclip_wx:
6133  case RISCVVector::BI__builtin_rvv_vnclipu_wv:
6134  case RISCVVector::BI__builtin_rvv_vnclipu_wx:
6135  return BuiltinConstantArgRange(TheCall, 2, 0, 3);
6136  case RISCVVector::BI__builtin_rvv_vaaddu_vv_tu:
6137  case RISCVVector::BI__builtin_rvv_vaaddu_vx_tu:
6138  case RISCVVector::BI__builtin_rvv_vaadd_vv_tu:
6139  case RISCVVector::BI__builtin_rvv_vaadd_vx_tu:
6140  case RISCVVector::BI__builtin_rvv_vasubu_vv_tu:
6141  case RISCVVector::BI__builtin_rvv_vasubu_vx_tu:
6142  case RISCVVector::BI__builtin_rvv_vasub_vv_tu:
6143  case RISCVVector::BI__builtin_rvv_vasub_vx_tu:
6144  case RISCVVector::BI__builtin_rvv_vsmul_vv_tu:
6145  case RISCVVector::BI__builtin_rvv_vsmul_vx_tu:
6146  case RISCVVector::BI__builtin_rvv_vssra_vv_tu:
6147  case RISCVVector::BI__builtin_rvv_vssra_vx_tu:
6148  case RISCVVector::BI__builtin_rvv_vssrl_vv_tu:
6149  case RISCVVector::BI__builtin_rvv_vssrl_vx_tu:
6150  case RISCVVector::BI__builtin_rvv_vnclip_wv_tu:
6151  case RISCVVector::BI__builtin_rvv_vnclip_wx_tu:
6152  case RISCVVector::BI__builtin_rvv_vnclipu_wv_tu:
6153  case RISCVVector::BI__builtin_rvv_vnclipu_wx_tu:
6154  case RISCVVector::BI__builtin_rvv_vaaddu_vv_m:
6155  case RISCVVector::BI__builtin_rvv_vaaddu_vx_m:
6156  case RISCVVector::BI__builtin_rvv_vaadd_vv_m:
6157  case RISCVVector::BI__builtin_rvv_vaadd_vx_m:
6158  case RISCVVector::BI__builtin_rvv_vasubu_vv_m:
6159  case RISCVVector::BI__builtin_rvv_vasubu_vx_m:
6160  case RISCVVector::BI__builtin_rvv_vasub_vv_m:
6161  case RISCVVector::BI__builtin_rvv_vasub_vx_m:
6162  case RISCVVector::BI__builtin_rvv_vsmul_vv_m:
6163  case RISCVVector::BI__builtin_rvv_vsmul_vx_m:
6164  case RISCVVector::BI__builtin_rvv_vssra_vv_m:
6165  case RISCVVector::BI__builtin_rvv_vssra_vx_m:
6166  case RISCVVector::BI__builtin_rvv_vssrl_vv_m:
6167  case RISCVVector::BI__builtin_rvv_vssrl_vx_m:
6168  case RISCVVector::BI__builtin_rvv_vnclip_wv_m:
6169  case RISCVVector::BI__builtin_rvv_vnclip_wx_m:
6170  case RISCVVector::BI__builtin_rvv_vnclipu_wv_m:
6171  case RISCVVector::BI__builtin_rvv_vnclipu_wx_m:
6172  return BuiltinConstantArgRange(TheCall, 3, 0, 3);
6173  case RISCVVector::BI__builtin_rvv_vaaddu_vv_tum:
6174  case RISCVVector::BI__builtin_rvv_vaaddu_vv_tumu:
6175  case RISCVVector::BI__builtin_rvv_vaaddu_vv_mu:
6176  case RISCVVector::BI__builtin_rvv_vaaddu_vx_tum:
6177  case RISCVVector::BI__builtin_rvv_vaaddu_vx_tumu:
6178  case RISCVVector::BI__builtin_rvv_vaaddu_vx_mu:
6179  case RISCVVector::BI__builtin_rvv_vaadd_vv_tum:
6180  case RISCVVector::BI__builtin_rvv_vaadd_vv_tumu:
6181  case RISCVVector::BI__builtin_rvv_vaadd_vv_mu:
6182  case RISCVVector::BI__builtin_rvv_vaadd_vx_tum:
6183  case RISCVVector::BI__builtin_rvv_vaadd_vx_tumu:
6184  case RISCVVector::BI__builtin_rvv_vaadd_vx_mu:
6185  case RISCVVector::BI__builtin_rvv_vasubu_vv_tum:
6186  case RISCVVector::BI__builtin_rvv_vasubu_vv_tumu:
6187  case RISCVVector::BI__builtin_rvv_vasubu_vv_mu:
6188  case RISCVVector::BI__builtin_rvv_vasubu_vx_tum:
6189  case RISCVVector::BI__builtin_rvv_vasubu_vx_tumu:
6190  case RISCVVector::BI__builtin_rvv_vasubu_vx_mu:
6191  case RISCVVector::BI__builtin_rvv_vasub_vv_tum:
6192  case RISCVVector::BI__builtin_rvv_vasub_vv_tumu:
6193  case RISCVVector::BI__builtin_rvv_vasub_vv_mu:
6194  case RISCVVector::BI__builtin_rvv_vasub_vx_tum:
6195  case RISCVVector::BI__builtin_rvv_vasub_vx_tumu:
6196  case RISCVVector::BI__builtin_rvv_vasub_vx_mu:
6197  case RISCVVector::BI__builtin_rvv_vsmul_vv_mu:
6198  case RISCVVector::BI__builtin_rvv_vsmul_vx_mu:
6199  case RISCVVector::BI__builtin_rvv_vssra_vv_mu:
6200  case RISCVVector::BI__builtin_rvv_vssra_vx_mu:
6201  case RISCVVector::BI__builtin_rvv_vssrl_vv_mu:
6202  case RISCVVector::BI__builtin_rvv_vssrl_vx_mu:
6203  case RISCVVector::BI__builtin_rvv_vnclip_wv_mu:
6204  case RISCVVector::BI__builtin_rvv_vnclip_wx_mu:
6205  case RISCVVector::BI__builtin_rvv_vnclipu_wv_mu:
6206  case RISCVVector::BI__builtin_rvv_vnclipu_wx_mu:
6207  case RISCVVector::BI__builtin_rvv_vsmul_vv_tum:
6208  case RISCVVector::BI__builtin_rvv_vsmul_vx_tum:
6209  case RISCVVector::BI__builtin_rvv_vssra_vv_tum:
6210  case RISCVVector::BI__builtin_rvv_vssra_vx_tum:
6211  case RISCVVector::BI__builtin_rvv_vssrl_vv_tum:
6212  case RISCVVector::BI__builtin_rvv_vssrl_vx_tum:
6213  case RISCVVector::BI__builtin_rvv_vnclip_wv_tum:
6214  case RISCVVector::BI__builtin_rvv_vnclip_wx_tum:
6215  case RISCVVector::BI__builtin_rvv_vnclipu_wv_tum:
6216  case RISCVVector::BI__builtin_rvv_vnclipu_wx_tum:
6217  case RISCVVector::BI__builtin_rvv_vsmul_vv_tumu:
6218  case RISCVVector::BI__builtin_rvv_vsmul_vx_tumu:
6219  case RISCVVector::BI__builtin_rvv_vssra_vv_tumu:
6220  case RISCVVector::BI__builtin_rvv_vssra_vx_tumu:
6221  case RISCVVector::BI__builtin_rvv_vssrl_vv_tumu:
6222  case RISCVVector::BI__builtin_rvv_vssrl_vx_tumu:
6223  case RISCVVector::BI__builtin_rvv_vnclip_wv_tumu:
6224  case RISCVVector::BI__builtin_rvv_vnclip_wx_tumu:
6225  case RISCVVector::BI__builtin_rvv_vnclipu_wv_tumu:
6226  case RISCVVector::BI__builtin_rvv_vnclipu_wx_tumu:
6227  return BuiltinConstantArgRange(TheCall, 4, 0, 3);
6228  case RISCVVector::BI__builtin_rvv_vfsqrt_v_rm:
6229  case RISCVVector::BI__builtin_rvv_vfrec7_v_rm:
6230  case RISCVVector::BI__builtin_rvv_vfcvt_x_f_v_rm:
6231  case RISCVVector::BI__builtin_rvv_vfcvt_xu_f_v_rm:
6232  case RISCVVector::BI__builtin_rvv_vfcvt_f_x_v_rm:
6233  case RISCVVector::BI__builtin_rvv_vfcvt_f_xu_v_rm:
6234  case RISCVVector::BI__builtin_rvv_vfwcvt_x_f_v_rm:
6235  case RISCVVector::BI__builtin_rvv_vfwcvt_xu_f_v_rm:
6236  case RISCVVector::BI__builtin_rvv_vfncvt_x_f_w_rm:
6237  case RISCVVector::BI__builtin_rvv_vfncvt_xu_f_w_rm:
6238  case RISCVVector::BI__builtin_rvv_vfncvt_f_x_w_rm:
6239  case RISCVVector::BI__builtin_rvv_vfncvt_f_xu_w_rm:
6240  case RISCVVector::BI__builtin_rvv_vfncvt_f_f_w_rm:
6241  return BuiltinConstantArgRange(TheCall, 1, 0, 4);
6242  case RISCVVector::BI__builtin_rvv_vfadd_vv_rm:
6243  case RISCVVector::BI__builtin_rvv_vfadd_vf_rm:
6244  case RISCVVector::BI__builtin_rvv_vfsub_vv_rm:
6245  case RISCVVector::BI__builtin_rvv_vfsub_vf_rm:
6246  case RISCVVector::BI__builtin_rvv_vfrsub_vf_rm:
6247  case RISCVVector::BI__builtin_rvv_vfwadd_vv_rm:
6248  case RISCVVector::BI__builtin_rvv_vfwadd_vf_rm:
6249  case RISCVVector::BI__builtin_rvv_vfwsub_vv_rm:
6250  case RISCVVector::BI__builtin_rvv_vfwsub_vf_rm:
6251  case RISCVVector::BI__builtin_rvv_vfwadd_wv_rm:
6252  case RISCVVector::BI__builtin_rvv_vfwadd_wf_rm:
6253  case RISCVVector::BI__builtin_rvv_vfwsub_wv_rm:
6254  case RISCVVector::BI__builtin_rvv_vfwsub_wf_rm:
6255  case RISCVVector::BI__builtin_rvv_vfmul_vv_rm:
6256  case RISCVVector::BI__builtin_rvv_vfmul_vf_rm:
6257  case RISCVVector::BI__builtin_rvv_vfdiv_vv_rm:
6258  case RISCVVector::BI__builtin_rvv_vfdiv_vf_rm:
6259  case RISCVVector::BI__builtin_rvv_vfrdiv_vf_rm:
6260  case RISCVVector::BI__builtin_rvv_vfwmul_vv_rm:
6261  case RISCVVector::BI__builtin_rvv_vfwmul_vf_rm:
6262  case RISCVVector::BI__builtin_rvv_vfredosum_vs_rm:
6263  case RISCVVector::BI__builtin_rvv_vfredusum_vs_rm:
6264  case RISCVVector::BI__builtin_rvv_vfwredosum_vs_rm:
6265  case RISCVVector::BI__builtin_rvv_vfwredusum_vs_rm:
6266  case RISCVVector::BI__builtin_rvv_vfsqrt_v_rm_tu:
6267  case RISCVVector::BI__builtin_rvv_vfrec7_v_rm_tu:
6268  case RISCVVector::BI__builtin_rvv_vfcvt_x_f_v_rm_tu:
6269  case RISCVVector::BI__builtin_rvv_vfcvt_xu_f_v_rm_tu:
6270  case RISCVVector::BI__builtin_rvv_vfcvt_f_x_v_rm_tu:
6271  case RISCVVector::BI__builtin_rvv_vfcvt_f_xu_v_rm_tu:
6272  case RISCVVector::BI__builtin_rvv_vfwcvt_x_f_v_rm_tu:
6273  case RISCVVector::BI__builtin_rvv_vfwcvt_xu_f_v_rm_tu:
6274  case RISCVVector::BI__builtin_rvv_vfncvt_x_f_w_rm_tu:
6275  case RISCVVector::BI__builtin_rvv_vfncvt_xu_f_w_rm_tu:
6276  case RISCVVector::BI__builtin_rvv_vfncvt_f_x_w_rm_tu:
6277  case RISCVVector::BI__builtin_rvv_vfncvt_f_xu_w_rm_tu:
6278  case RISCVVector::BI__builtin_rvv_vfncvt_f_f_w_rm_tu:
6279  case RISCVVector::BI__builtin_rvv_vfsqrt_v_rm_m:
6280  case RISCVVector::BI__builtin_rvv_vfrec7_v_rm_m:
6281  case RISCVVector::BI__builtin_rvv_vfcvt_x_f_v_rm_m:
6282  case RISCVVector::BI__builtin_rvv_vfcvt_xu_f_v_rm_m:
6283  case RISCVVector::BI__builtin_rvv_vfcvt_f_x_v_rm_m:
6284  case RISCVVector::BI__builtin_rvv_vfcvt_f_xu_v_rm_m:
6285  case RISCVVector::BI__builtin_rvv_vfwcvt_x_f_v_rm_m:
6286  case RISCVVector::BI__builtin_rvv_vfwcvt_xu_f_v_rm_m:
6287  case RISCVVector::BI__builtin_rvv_vfncvt_x_f_w_rm_m:
6288  case RISCVVector::BI__builtin_rvv_vfncvt_xu_f_w_rm_m:
6289  case RISCVVector::BI__builtin_rvv_vfncvt_f_x_w_rm_m:
6290  case RISCVVector::BI__builtin_rvv_vfncvt_f_xu_w_rm_m:
6291  case RISCVVector::BI__builtin_rvv_vfncvt_f_f_w_rm_m:
6292  return BuiltinConstantArgRange(TheCall, 2, 0, 4);
6293  case RISCVVector::BI__builtin_rvv_vfadd_vv_rm_tu:
6294  case RISCVVector::BI__builtin_rvv_vfadd_vf_rm_tu:
6295  case RISCVVector::BI__builtin_rvv_vfsub_vv_rm_tu:
6296  case RISCVVector::BI__builtin_rvv_vfsub_vf_rm_tu:
6297  case RISCVVector::BI__builtin_rvv_vfrsub_vf_rm_tu:
6298  case RISCVVector::BI__builtin_rvv_vfwadd_vv_rm_tu:
6299  case RISCVVector::BI__builtin_rvv_vfwadd_vf_rm_tu:
6300  case RISCVVector::BI__builtin_rvv_vfwsub_vv_rm_tu:
6301  case RISCVVector::BI__builtin_rvv_vfwsub_vf_rm_tu:
6302  case RISCVVector::BI__builtin_rvv_vfwadd_wv_rm_tu:
6303  case RISCVVector::BI__builtin_rvv_vfwadd_wf_rm_tu:
6304  case RISCVVector::BI__builtin_rvv_vfwsub_wv_rm_tu:
6305  case RISCVVector::BI__builtin_rvv_vfwsub_wf_rm_tu:
6306  case RISCVVector::BI__builtin_rvv_vfmul_vv_rm_tu:
6307  case RISCVVector::BI__builtin_rvv_vfmul_vf_rm_tu:
6308  case RISCVVector::BI__builtin_rvv_vfdiv_vv_rm_tu:
6309  case RISCVVector::BI__builtin_rvv_vfdiv_vf_rm_tu:
6310  case RISCVVector::BI__builtin_rvv_vfrdiv_vf_rm_tu:
6311  case RISCVVector::BI__builtin_rvv_vfwmul_vv_rm_tu:
6312  case RISCVVector::BI__builtin_rvv_vfwmul_vf_rm_tu:
6313  case RISCVVector::BI__builtin_rvv_vfredosum_vs_rm_tu:
6314  case RISCVVector::BI__builtin_rvv_vfredusum_vs_rm_tu:
6315  case RISCVVector::BI__builtin_rvv_vfwredosum_vs_rm_tu:
6316  case RISCVVector::BI__builtin_rvv_vfwredusum_vs_rm_tu:
6317  case RISCVVector::BI__builtin_rvv_vfmacc_vv_rm:
6318  case RISCVVector::BI__builtin_rvv_vfmacc_vf_rm:
6319  case RISCVVector::BI__builtin_rvv_vfnmacc_vv_rm:
6320  case RISCVVector::BI__builtin_rvv_vfnmacc_vf_rm:
6321  case RISCVVector::BI__builtin_rvv_vfmsac_vv_rm:
6322  case RISCVVector::BI__builtin_rvv_vfmsac_vf_rm:
6323  case RISCVVector::BI__builtin_rvv_vfnmsac_vv_rm:
6324  case RISCVVector::BI__builtin_rvv_vfnmsac_vf_rm:
6325  case RISCVVector::BI__builtin_rvv_vfmadd_vv_rm:
6326  case RISCVVector::BI__builtin_rvv_vfmadd_vf_rm:
6327  case RISCVVector::BI__builtin_rvv_vfnmadd_vv_rm:
6328  case RISCVVector::BI__builtin_rvv_vfnmadd_vf_rm:
6329  case RISCVVector::BI__builtin_rvv_vfmsub_vv_rm:
6330  case RISCVVector::BI__builtin_rvv_vfmsub_vf_rm:
6331  case RISCVVector::BI__builtin_rvv_vfnmsub_vv_rm:
6332  case RISCVVector::BI__builtin_rvv_vfnmsub_vf_rm:
6333  case RISCVVector::BI__builtin_rvv_vfwmacc_vv_rm:
6334  case RISCVVector::BI__builtin_rvv_vfwmacc_vf_rm:
6335  case RISCVVector::BI__builtin_rvv_vfwnmacc_vv_rm:
6336  case RISCVVector::BI__builtin_rvv_vfwnmacc_vf_rm:
6337  case RISCVVector::BI__builtin_rvv_vfwmsac_vv_rm:
6338  case RISCVVector::BI__builtin_rvv_vfwmsac_vf_rm:
6339  case RISCVVector::BI__builtin_rvv_vfwnmsac_vv_rm:
6340  case RISCVVector::BI__builtin_rvv_vfwnmsac_vf_rm:
6341  case RISCVVector::BI__builtin_rvv_vfmacc_vv_rm_tu:
6342  case RISCVVector::BI__builtin_rvv_vfmacc_vf_rm_tu:
6343  case RISCVVector::BI__builtin_rvv_vfnmacc_vv_rm_tu:
6344  case RISCVVector::BI__builtin_rvv_vfnmacc_vf_rm_tu:
6345  case RISCVVector::BI__builtin_rvv_vfmsac_vv_rm_tu:
6346  case RISCVVector::BI__builtin_rvv_vfmsac_vf_rm_tu:
6347  case RISCVVector::BI__builtin_rvv_vfnmsac_vv_rm_tu:
6348  case RISCVVector::BI__builtin_rvv_vfnmsac_vf_rm_tu:
6349  case RISCVVector::BI__builtin_rvv_vfmadd_vv_rm_tu:
6350  case RISCVVector::BI__builtin_rvv_vfmadd_vf_rm_tu:
6351  case RISCVVector::BI__builtin_rvv_vfnmadd_vv_rm_tu:
6352  case RISCVVector::BI__builtin_rvv_vfnmadd_vf_rm_tu:
6353  case RISCVVector::BI__builtin_rvv_vfmsub_vv_rm_tu:
6354  case RISCVVector::BI__builtin_rvv_vfmsub_vf_rm_tu:
6355  case RISCVVector::BI__builtin_rvv_vfnmsub_vv_rm_tu:
6356  case RISCVVector::BI__builtin_rvv_vfnmsub_vf_rm_tu:
6357  case RISCVVector::BI__builtin_rvv_vfwmacc_vv_rm_tu:
6358  case RISCVVector::BI__builtin_rvv_vfwmacc_vf_rm_tu:
6359  case RISCVVector::BI__builtin_rvv_vfwnmacc_vv_rm_tu:
6360  case RISCVVector::BI__builtin_rvv_vfwnmacc_vf_rm_tu:
6361  case RISCVVector::BI__builtin_rvv_vfwmsac_vv_rm_tu:
6362  case RISCVVector::BI__builtin_rvv_vfwmsac_vf_rm_tu:
6363  case RISCVVector::BI__builtin_rvv_vfwnmsac_vv_rm_tu:
6364  case RISCVVector::BI__builtin_rvv_vfwnmsac_vf_rm_tu:
6365  case RISCVVector::BI__builtin_rvv_vfadd_vv_rm_m:
6366  case RISCVVector::BI__builtin_rvv_vfadd_vf_rm_m:
6367  case RISCVVector::BI__builtin_rvv_vfsub_vv_rm_m:
6368  case RISCVVector::BI__builtin_rvv_vfsub_vf_rm_m:
6369  case RISCVVector::BI__builtin_rvv_vfrsub_vf_rm_m:
6370  case RISCVVector::BI__builtin_rvv_vfwadd_vv_rm_m:
6371  case RISCVVector::BI__builtin_rvv_vfwadd_vf_rm_m:
6372  case RISCVVector::BI__builtin_rvv_vfwsub_vv_rm_m:
6373  case RISCVVector::BI__builtin_rvv_vfwsub_vf_rm_m:
6374  case RISCVVector::BI__builtin_rvv_vfwadd_wv_rm_m:
6375  case RISCVVector::BI__builtin_rvv_vfwadd_wf_rm_m:
6376  case RISCVVector::BI__builtin_rvv_vfwsub_wv_rm_m:
6377  case RISCVVector::BI__builtin_rvv_vfwsub_wf_rm_m:
6378  case RISCVVector::BI__builtin_rvv_vfmul_vv_rm_m:
6379  case RISCVVector::BI__builtin_rvv_vfmul_vf_rm_m:
6380  case RISCVVector::BI__builtin_rvv_vfdiv_vv_rm_m:
6381  case RISCVVector::BI__builtin_rvv_vfdiv_vf_rm_m:
6382  case RISCVVector::BI__builtin_rvv_vfrdiv_vf_rm_m:
6383  case RISCVVector::BI__builtin_rvv_vfwmul_vv_rm_m:
6384  case RISCVVector::BI__builtin_rvv_vfwmul_vf_rm_m:
6385  case RISCVVector::BI__builtin_rvv_vfredosum_vs_rm_m:
6386  case RISCVVector::BI__builtin_rvv_vfredusum_vs_rm_m:
6387  case RISCVVector::BI__builtin_rvv_vfwredosum_vs_rm_m:
6388  case RISCVVector::BI__builtin_rvv_vfwredusum_vs_rm_m:
6389  case RISCVVector::BI__builtin_rvv_vfsqrt_v_rm_tum:
6390  case RISCVVector::BI__builtin_rvv_vfrec7_v_rm_tum:
6391  case RISCVVector::BI__builtin_rvv_vfcvt_x_f_v_rm_tum:
6392  case RISCVVector::BI__builtin_rvv_vfcvt_xu_f_v_rm_tum:
6393  case RISCVVector::BI__builtin_rvv_vfcvt_f_x_v_rm_tum:
6394  case RISCVVector::BI__builtin_rvv_vfcvt_f_xu_v_rm_tum:
6395  case RISCVVector::BI__builtin_rvv_vfwcvt_x_f_v_rm_tum:
6396  case RISCVVector::BI__builtin_rvv_vfwcvt_xu_f_v_rm_tum:
6397  case RISCVVector::BI__builtin_rvv_vfncvt_x_f_w_rm_tum:
6398  case RISCVVector::BI__builtin_rvv_vfncvt_xu_f_w_rm_tum:
6399  case RISCVVector::BI__builtin_rvv_vfncvt_f_x_w_rm_tum:
6400  case RISCVVector::BI__builtin_rvv_vfncvt_f_xu_w_rm_tum:
6401  case RISCVVector::BI__builtin_rvv_vfncvt_f_f_w_rm_tum:
6402  case RISCVVector::BI__builtin_rvv_vfsqrt_v_rm_tumu:
6403  case RISCVVector::BI__builtin_rvv_vfrec7_v_rm_tumu:
6404  case RISCVVector::BI__builtin_rvv_vfcvt_x_f_v_rm_tumu:
6405  case RISCVVector::BI__builtin_rvv_vfcvt_xu_f_v_rm_tumu:
6406  case RISCVVector::BI__builtin_rvv_vfcvt_f_x_v_rm_tumu:
6407  case RISCVVector::BI__builtin_rvv_vfcvt_f_xu_v_rm_tumu:
6408  case RISCVVector::BI__builtin_rvv_vfwcvt_x_f_v_rm_tumu:
6409  case RISCVVector::BI__builtin_rvv_vfwcvt_xu_f_v_rm_tumu:
6410  case RISCVVector::BI__builtin_rvv_vfncvt_x_f_w_rm_tumu:
6411  case RISCVVector::BI__builtin_rvv_vfncvt_xu_f_w_rm_tumu:
6412  case RISCVVector::BI__builtin_rvv_vfncvt_f_x_w_rm_tumu:
6413  case RISCVVector::BI__builtin_rvv_vfncvt_f_xu_w_rm_tumu:
6414  case RISCVVector::BI__builtin_rvv_vfncvt_f_f_w_rm_tumu:
6415  case RISCVVector::BI__builtin_rvv_vfsqrt_v_rm_mu:
6416  case RISCVVector::BI__builtin_rvv_vfrec7_v_rm_mu:
6417  case RISCVVector::BI__builtin_rvv_vfcvt_x_f_v_rm_mu:
6418  case RISCVVector::BI__builtin_rvv_vfcvt_xu_f_v_rm_mu:
6419  case RISCVVector::BI__builtin_rvv_vfcvt_f_x_v_rm_mu:
6420  case RISCVVector::BI__builtin_rvv_vfcvt_f_xu_v_rm_mu:
6421  case RISCVVector::BI__builtin_rvv_vfwcvt_x_f_v_rm_mu:
6422  case RISCVVector::BI__builtin_rvv_vfwcvt_xu_f_v_rm_mu:
6423  case RISCVVector::BI__builtin_rvv_vfncvt_x_f_w_rm_mu:
6424  case RISCVVector::BI__builtin_rvv_vfncvt_xu_f_w_rm_mu:
6425  case RISCVVector::BI__builtin_rvv_vfncvt_f_x_w_rm_mu:
6426  case RISCVVector::BI__builtin_rvv_vfncvt_f_xu_w_rm_mu:
6427  case RISCVVector::BI__builtin_rvv_vfncvt_f_f_w_rm_mu:
6428  return BuiltinConstantArgRange(TheCall, 3, 0, 4);
6429  case RISCVVector::BI__builtin_rvv_vfmacc_vv_rm_m:
6430  case RISCVVector::BI__builtin_rvv_vfmacc_vf_rm_m:
6431  case RISCVVector::BI__builtin_rvv_vfnmacc_vv_rm_m:
6432  case RISCVVector::BI__builtin_rvv_vfnmacc_vf_rm_m:
6433  case RISCVVector::BI__builtin_rvv_vfmsac_vv_rm_m:
6434  case RISCVVector::BI__builtin_rvv_vfmsac_vf_rm_m:
6435  case RISCVVector::BI__builtin_rvv_vfnmsac_vv_rm_m:
6436  case RISCVVector::BI__builtin_rvv_vfnmsac_vf_rm_m:
6437  case RISCVVector::BI__builtin_rvv_vfmadd_vv_rm_m:
6438  case RISCVVector::BI__builtin_rvv_vfmadd_vf_rm_m:
6439  case RISCVVector::BI__builtin_rvv_vfnmadd_vv_rm_m:
6440  case RISCVVector::BI__builtin_rvv_vfnmadd_vf_rm_m:
6441  case RISCVVector::BI__builtin_rvv_vfmsub_vv_rm_m:
6442  case RISCVVector::BI__builtin_rvv_vfmsub_vf_rm_m:
6443  case RISCVVector::BI__builtin_rvv_vfnmsub_vv_rm_m:
6444  case RISCVVector::BI__builtin_rvv_vfnmsub_vf_rm_m:
6445  case RISCVVector::BI__builtin_rvv_vfwmacc_vv_rm_m:
6446  case RISCVVector::BI__builtin_rvv_vfwmacc_vf_rm_m:
6447  case RISCVVector::BI__builtin_rvv_vfwnmacc_vv_rm_m:
6448  case RISCVVector::BI__builtin_rvv_vfwnmacc_vf_rm_m:
6449  case RISCVVector::BI__builtin_rvv_vfwmsac_vv_rm_m:
6450  case RISCVVector::BI__builtin_rvv_vfwmsac_vf_rm_m:
6451  case RISCVVector::BI__builtin_rvv_vfwnmsac_vv_rm_m:
6452  case RISCVVector::BI__builtin_rvv_vfwnmsac_vf_rm_m:
6453  case RISCVVector::BI__builtin_rvv_vfadd_vv_rm_tum:
6454  case RISCVVector::BI__builtin_rvv_vfadd_vf_rm_tum:
6455  case RISCVVector::BI__builtin_rvv_vfsub_vv_rm_tum:
6456  case RISCVVector::BI__builtin_rvv_vfsub_vf_rm_tum:
6457  case RISCVVector::BI__builtin_rvv_vfrsub_vf_rm_tum:
6458  case RISCVVector::BI__builtin_rvv_vfwadd_vv_rm_tum:
6459  case RISCVVector::BI__builtin_rvv_vfwadd_vf_rm_tum:
6460  case RISCVVector::BI__builtin_rvv_vfwsub_vv_rm_tum:
6461  case RISCVVector::BI__builtin_rvv_vfwsub_vf_rm_tum:
6462  case RISCVVector::BI__builtin_rvv_vfwadd_wv_rm_tum:
6463  case RISCVVector::BI__builtin_rvv_vfwadd_wf_rm_tum:
6464  case RISCVVector::BI__builtin_rvv_vfwsub_wv_rm_tum:
6465  case RISCVVector::BI__builtin_rvv_vfwsub_wf_rm_tum:
6466  case RISCVVector::BI__builtin_rvv_vfmul_vv_rm_tum:
6467  case RISCVVector::BI__builtin_rvv_vfmul_vf_rm_tum:
6468  case RISCVVector::BI__builtin_rvv_vfdiv_vv_rm_tum:
6469  case RISCVVector::BI__builtin_rvv_vfdiv_vf_rm_tum:
6470  case RISCVVector::BI__builtin_rvv_vfrdiv_vf_rm_tum:
6471  case RISCVVector::BI__builtin_rvv_vfwmul_vv_rm_tum:
6472  case RISCVVector::BI__builtin_rvv_vfwmul_vf_rm_tum:
6473  case RISCVVector::BI__builtin_rvv_vfmacc_vv_rm_tum:
6474  case RISCVVector::BI__builtin_rvv_vfmacc_vf_rm_tum:
6475  case RISCVVector::BI__builtin_rvv_vfnmacc_vv_rm_tum:
6476  case RISCVVector::BI__builtin_rvv_vfnmacc_vf_rm_tum:
6477  case RISCVVector::BI__builtin_rvv_vfmsac_vv_rm_tum:
6478  case RISCVVector::BI__builtin_rvv_vfmsac_vf_rm_tum:
6479  case RISCVVector::BI__builtin_rvv_vfnmsac_vv_rm_tum:
6480  case RISCVVector::BI__builtin_rvv_vfnmsac_vf_rm_tum:
6481  case RISCVVector::BI__builtin_rvv_vfmadd_vv_rm_tum:
6482  case RISCVVector::BI__builtin_rvv_vfmadd_vf_rm_tum:
6483  case RISCVVector::BI__builtin_rvv_vfnmadd_vv_rm_tum:
6484  case RISCVVector::BI__builtin_rvv_vfnmadd_vf_rm_tum:
6485  case RISCVVector::BI__builtin_rvv_vfmsub_vv_rm_tum:
6486  case RISCVVector::BI__builtin_rvv_vfmsub_vf_rm_tum:
6487  case RISCVVector::BI__builtin_rvv_vfnmsub_vv_rm_tum:
6488  case RISCVVector::BI__builtin_rvv_vfnmsub_vf_rm_tum:
6489  case RISCVVector::BI__builtin_rvv_vfwmacc_vv_rm_tum:
6490  case RISCVVector::BI__builtin_rvv_vfwmacc_vf_rm_tum:
6491  case RISCVVector::BI__builtin_rvv_vfwnmacc_vv_rm_tum:
6492  case RISCVVector::BI__builtin_rvv_vfwnmacc_vf_rm_tum:
6493  case RISCVVector::BI__builtin_rvv_vfwmsac_vv_rm_tum:
6494  case RISCVVector::BI__builtin_rvv_vfwmsac_vf_rm_tum:
6495  case RISCVVector::BI__builtin_rvv_vfwnmsac_vv_rm_tum:
6496  case RISCVVector::BI__builtin_rvv_vfwnmsac_vf_rm_tum:
6497  case RISCVVector::BI__builtin_rvv_vfredosum_vs_rm_tum:
6498  case RISCVVector::BI__builtin_rvv_vfredusum_vs_rm_tum:
6499  case RISCVVector::BI__builtin_rvv_vfwredosum_vs_rm_tum:
6500  case RISCVVector::BI__builtin_rvv_vfwredusum_vs_rm_tum:
6501  case RISCVVector::BI__builtin_rvv_vfadd_vv_rm_tumu:
6502  case RISCVVector::BI__builtin_rvv_vfadd_vf_rm_tumu:
6503  case RISCVVector::BI__builtin_rvv_vfsub_vv_rm_tumu:
6504  case RISCVVector::BI__builtin_rvv_vfsub_vf_rm_tumu:
6505  case RISCVVector::BI__builtin_rvv_vfrsub_vf_rm_tumu:
6506  case RISCVVector::BI__builtin_rvv_vfwadd_vv_rm_tumu:
6507  case RISCVVector::BI__builtin_rvv_vfwadd_vf_rm_tumu:
6508  case RISCVVector::BI__builtin_rvv_vfwsub_vv_rm_tumu:
6509  case RISCVVector::BI__builtin_rvv_vfwsub_vf_rm_tumu:
6510  case RISCVVector::BI__builtin_rvv_vfwadd_wv_rm_tumu:
6511  case RISCVVector::BI__builtin_rvv_vfwadd_wf_rm_tumu:
6512  case RISCVVector::BI__builtin_rvv_vfwsub_wv_rm_tumu:
6513  case RISCVVector::BI__builtin_rvv_vfwsub_wf_rm_tumu:
6514  case RISCVVector::BI__builtin_rvv_vfmul_vv_rm_tumu:
6515  case RISCVVector::BI__builtin_rvv_vfmul_vf_rm_tumu:
6516  case RISCVVector::BI__builtin_rvv_vfdiv_vv_rm_tumu:
6517  case RISCVVector::BI__builtin_rvv_vfdiv_vf_rm_tumu:
6518  case RISCVVector::BI__builtin_rvv_vfrdiv_vf_rm_tumu:
6519  case RISCVVector::BI__builtin_rvv_vfwmul_vv_rm_tumu:
6520  case RISCVVector::BI__builtin_rvv_vfwmul_vf_rm_tumu:
6521  case RISCVVector::BI__builtin_rvv_vfmacc_vv_rm_tumu:
6522  case RISCVVector::BI__builtin_rvv_vfmacc_vf_rm_tumu:
6523  case RISCVVector::BI__builtin_rvv_vfnmacc_vv_rm_tumu:
6524  case RISCVVector::BI__builtin_rvv_vfnmacc_vf_rm_tumu:
6525  case RISCVVector::BI__builtin_rvv_vfmsac_vv_rm_tumu:
6526  case RISCVVector::BI__builtin_rvv_vfmsac_vf_rm_tumu:
6527  case RISCVVector::BI__builtin_rvv_vfnmsac_vv_rm_tumu:
6528  case RISCVVector::BI__builtin_rvv_vfnmsac_vf_rm_tumu:
6529  case RISCVVector::BI__builtin_rvv_vfmadd_vv_rm_tumu:
6530  case RISCVVector::BI__builtin_rvv_vfmadd_vf_rm_tumu:
6531  case RISCVVector::BI__builtin_rvv_vfnmadd_vv_rm_tumu:
6532  case RISCVVector::BI__builtin_rvv_vfnmadd_vf_rm_tumu:
6533  case RISCVVector::BI__builtin_rvv_vfmsub_vv_rm_tumu:
6534  case RISCVVector::BI__builtin_rvv_vfmsub_vf_rm_tumu:
6535  case RISCVVector::BI__builtin_rvv_vfnmsub_vv_rm_tumu:
6536  case RISCVVector::BI__builtin_rvv_vfnmsub_vf_rm_tumu:
6537  case RISCVVector::BI__builtin_rvv_vfwmacc_vv_rm_tumu:
6538  case RISCVVector::BI__builtin_rvv_vfwmacc_vf_rm_tumu:
6539  case RISCVVector::BI__builtin_rvv_vfwnmacc_vv_rm_tumu:
6540  case RISCVVector::BI__builtin_rvv_vfwnmacc_vf_rm_tumu:
6541  case RISCVVector::BI__builtin_rvv_vfwmsac_vv_rm_tumu:
6542  case RISCVVector::BI__builtin_rvv_vfwmsac_vf_rm_tumu:
6543  case RISCVVector::BI__builtin_rvv_vfwnmsac_vv_rm_tumu:
6544  case RISCVVector::BI__builtin_rvv_vfwnmsac_vf_rm_tumu:
6545  case RISCVVector::BI__builtin_rvv_vfadd_vv_rm_mu:
6546  case RISCVVector::BI__builtin_rvv_vfadd_vf_rm_mu:
6547  case RISCVVector::BI__builtin_rvv_vfsub_vv_rm_mu:
6548  case RISCVVector::BI__builtin_rvv_vfsub_vf_rm_mu:
6549  case RISCVVector::BI__builtin_rvv_vfrsub_vf_rm_mu:
6550  case RISCVVector::BI__builtin_rvv_vfwadd_vv_rm_mu:
6551  case RISCVVector::BI__builtin_rvv_vfwadd_vf_rm_mu:
6552  case RISCVVector::BI__builtin_rvv_vfwsub_vv_rm_mu:
6553  case RISCVVector::BI__builtin_rvv_vfwsub_vf_rm_mu:
6554  case RISCVVector::BI__builtin_rvv_vfwadd_wv_rm_mu:
6555  case RISCVVector::BI__builtin_rvv_vfwadd_wf_rm_mu:
6556  case RISCVVector::BI__builtin_rvv_vfwsub_wv_rm_mu:
6557  case RISCVVector::BI__builtin_rvv_vfwsub_wf_rm_mu:
6558  case RISCVVector::BI__builtin_rvv_vfmul_vv_rm_mu:
6559  case RISCVVector::BI__builtin_rvv_vfmul_vf_rm_mu:
6560  case RISCVVector::BI__builtin_rvv_vfdiv_vv_rm_mu:
6561  case RISCVVector::BI__builtin_rvv_vfdiv_vf_rm_mu:
6562  case RISCVVector::BI__builtin_rvv_vfrdiv_vf_rm_mu:
6563  case RISCVVector::BI__builtin_rvv_vfwmul_vv_rm_mu:
6564  case RISCVVector::BI__builtin_rvv_vfwmul_vf_rm_mu:
6565  case RISCVVector::BI__builtin_rvv_vfmacc_vv_rm_mu:
6566  case RISCVVector::BI__builtin_rvv_vfmacc_vf_rm_mu:
6567  case RISCVVector::BI__builtin_rvv_vfnmacc_vv_rm_mu:
6568  case RISCVVector::BI__builtin_rvv_vfnmacc_vf_rm_mu:
6569  case RISCVVector::BI__builtin_rvv_vfmsac_vv_rm_mu:
6570  case RISCVVector::BI__builtin_rvv_vfmsac_vf_rm_mu:
6571  case RISCVVector::BI__builtin_rvv_vfnmsac_vv_rm_mu:
6572  case RISCVVector::BI__builtin_rvv_vfnmsac_vf_rm_mu:
6573  case RISCVVector::BI__builtin_rvv_vfmadd_vv_rm_mu:
6574  case RISCVVector::BI__builtin_rvv_vfmadd_vf_rm_mu:
6575  case RISCVVector::BI__builtin_rvv_vfnmadd_vv_rm_mu:
6576  case RISCVVector::BI__builtin_rvv_vfnmadd_vf_rm_mu:
6577  case RISCVVector::BI__builtin_rvv_vfmsub_vv_rm_mu:
6578  case RISCVVector::BI__builtin_rvv_vfmsub_vf_rm_mu:
6579  case RISCVVector::BI__builtin_rvv_vfnmsub_vv_rm_mu:
6580  case RISCVVector::BI__builtin_rvv_vfnmsub_vf_rm_mu:
6581  case RISCVVector::BI__builtin_rvv_vfwmacc_vv_rm_mu:
6582  case RISCVVector::BI__builtin_rvv_vfwmacc_vf_rm_mu:
6583  case RISCVVector::BI__builtin_rvv_vfwnmacc_vv_rm_mu:
6584  case RISCVVector::BI__builtin_rvv_vfwnmacc_vf_rm_mu:
6585  case RISCVVector::BI__builtin_rvv_vfwmsac_vv_rm_mu:
6586  case RISCVVector::BI__builtin_rvv_vfwmsac_vf_rm_mu:
6587  case RISCVVector::BI__builtin_rvv_vfwnmsac_vv_rm_mu:
6588  case RISCVVector::BI__builtin_rvv_vfwnmsac_vf_rm_mu:
6589  return BuiltinConstantArgRange(TheCall, 4, 0, 4);
6590  case RISCV::BI__builtin_riscv_ntl_load:
6591  case RISCV::BI__builtin_riscv_ntl_store:
6592  DeclRefExpr *DRE =
6593  cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6594  assert((BuiltinID == RISCV::BI__builtin_riscv_ntl_store ||
6595  BuiltinID == RISCV::BI__builtin_riscv_ntl_load) &&
6596  "Unexpected RISC-V nontemporal load/store builtin!");
6597  bool IsStore = BuiltinID == RISCV::BI__builtin_riscv_ntl_store;
6598  unsigned NumArgs = IsStore ? 3 : 2;
6599 
6600  if (checkArgCountAtLeast(*this, TheCall, NumArgs - 1))
6601  return true;
6602 
6603  if (checkArgCountAtMost(*this, TheCall, NumArgs))
6604  return true;
6605 
6606  // Domain value should be compile-time constant.
6607  // 2 <= domain <= 5
6608  if (TheCall->getNumArgs() == NumArgs &&
6609  BuiltinConstantArgRange(TheCall, NumArgs - 1, 2, 5))
6610  return true;
6611 
6612  Expr *PointerArg = TheCall->getArg(0);
6613  ExprResult PointerArgResult =
6614  DefaultFunctionArrayLvalueConversion(PointerArg);
6615 
6616  if (PointerArgResult.isInvalid())
6617  return true;
6618  PointerArg = PointerArgResult.get();
6619 
6620  const PointerType *PtrType = PointerArg->getType()->getAs<PointerType>();
6621  if (!PtrType) {
6622  Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6623  << PointerArg->getType() << PointerArg->getSourceRange();
6624  return true;
6625  }
6626 
6627  QualType ValType = PtrType->getPointeeType();
6628  ValType = ValType.getUnqualifiedType();
6629  if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6630  !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6631  !ValType->isVectorType() && !ValType->isRVVSizelessBuiltinType()) {
6632  Diag(DRE->getBeginLoc(),
6633  diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6634  << PointerArg->getType() << PointerArg->getSourceRange();
6635  return true;
6636  }
6637 
6638  if (!IsStore) {
6639  TheCall->setType(ValType);
6640  return false;
6641  }
6642 
6643  ExprResult ValArg = TheCall->getArg(1);
6645  Context, ValType, /*consume*/ false);
6646  ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6647  if (ValArg.isInvalid())
6648  return true;
6649 
6650  TheCall->setArg(1, ValArg.get());
6651  TheCall->setType(Context.VoidTy);
6652  return false;
6653  }
6654 
6655  return false;
6656 }
6657 
6658 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
6659  CallExpr *TheCall) {
6660  if (BuiltinID == SystemZ::BI__builtin_tabort) {
6661  Expr *Arg = TheCall->getArg(0);
6662  if (std::optional<llvm::APSInt> AbortCode =
6663  Arg->getIntegerConstantExpr(Context))
6664  if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
6665  return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
6666  << Arg->getSourceRange();
6667  }
6668 
6669  // For intrinsics which take an immediate value as part of the instruction,
6670  // range check them here.
6671  unsigned i = 0, l = 0, u = 0;
6672  switch (BuiltinID) {
6673  default: return false;
6674  case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
6675  case SystemZ::BI__builtin_s390_verimb:
6676  case SystemZ::BI__builtin_s390_verimh:
6677  case SystemZ::BI__builtin_s390_verimf:
6678  case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
6679  case SystemZ::BI__builtin_s390_vfaeb:
6680  case SystemZ::BI__builtin_s390_vfaeh:
6681  case SystemZ::BI__builtin_s390_vfaef:
6682  case SystemZ::BI__builtin_s390_vfaebs:
6683  case SystemZ::BI__builtin_s390_vfaehs:
6684  case SystemZ::BI__builtin_s390_vfaefs:
6685  case SystemZ::BI__builtin_s390_vfaezb:
6686  case SystemZ::BI__builtin_s390_vfaezh:
6687  case SystemZ::BI__builtin_s390_vfaezf:
6688  case SystemZ::BI__builtin_s390_vfaezbs:
6689  case SystemZ::BI__builtin_s390_vfaezhs:
6690  case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
6691  case SystemZ::BI__builtin_s390_vfisb:
6692  case SystemZ::BI__builtin_s390_vfidb:
6693  return BuiltinConstantArgRange(TheCall, 1, 0, 15) ||
6694  BuiltinConstantArgRange(TheCall, 2, 0, 15);
6695  case SystemZ::BI__builtin_s390_vftcisb:
6696  case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
6697  case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
6698  case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
6699  case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
6700  case SystemZ::BI__builtin_s390_vstrcb:
6701  case SystemZ::BI__builtin_s390_vstrch:
6702  case SystemZ::BI__builtin_s390_vstrcf:
6703  case SystemZ::BI__builtin_s390_vstrczb:
6704  case SystemZ::BI__builtin_s390_vstrczh:
6705  case SystemZ::BI__builtin_s390_vstrczf:
6706  case SystemZ::BI__builtin_s390_vstrcbs:
6707  case SystemZ::BI__builtin_s390_vstrchs:
6708  case SystemZ::BI__builtin_s390_vstrcfs:
6709  case SystemZ::BI__builtin_s390_vstrczbs:
6710  case SystemZ::BI__builtin_s390_vstrczhs:
6711  case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
6712  case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
6713  case SystemZ::BI__builtin_s390_vfminsb:
6714  case SystemZ::BI__builtin_s390_vfmaxsb:
6715  case SystemZ::BI__builtin_s390_vfmindb:
6716  case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
6717  case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
6718  case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
6719  case SystemZ::BI__builtin_s390_vclfnhs:
6720  case SystemZ::BI__builtin_s390_vclfnls:
6721  case SystemZ::BI__builtin_s390_vcfn:
6722  case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
6723  case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
6724  }
6725  return BuiltinConstantArgRange(TheCall, i, l, u);
6726 }
6727 
6728 bool Sema::CheckWebAssemblyBuiltinFunctionCall(const TargetInfo &TI,
6729  unsigned BuiltinID,
6730  CallExpr *TheCall) {
6731  switch (BuiltinID) {
6732  case WebAssembly::BI__builtin_wasm_ref_null_extern:
6733  return BuiltinWasmRefNullExtern(TheCall);
6734  case WebAssembly::BI__builtin_wasm_ref_null_func:
6735  return BuiltinWasmRefNullFunc(TheCall);
6736  case WebAssembly::BI__builtin_wasm_table_get:
6737  return BuiltinWasmTableGet(TheCall);
6738  case WebAssembly::BI__builtin_wasm_table_set:
6739  return BuiltinWasmTableSet(TheCall);
6740  case WebAssembly::BI__builtin_wasm_table_size:
6741  return BuiltinWasmTableSize(TheCall);
6742  case WebAssembly::BI__builtin_wasm_table_grow:
6743  return BuiltinWasmTableGrow(TheCall);
6744  case WebAssembly::BI__builtin_wasm_table_fill:
6745  return BuiltinWasmTableFill(TheCall);
6746  case WebAssembly::BI__builtin_wasm_table_copy:
6747  return BuiltinWasmTableCopy(TheCall);
6748  }
6749 
6750  return false;
6751 }
6752 
6753 void Sema::checkRVVTypeSupport(QualType Ty, SourceLocation Loc, Decl *D,
6754  const llvm::StringMap<bool> &FeatureMap) {
6757  unsigned EltSize = Context.getTypeSize(Info.ElementType);
6758  unsigned MinElts = Info.EC.getKnownMinValue();
6759 
6760  if (Info.ElementType->isSpecificBuiltinType(BuiltinType::Double) &&
6761  !FeatureMap.lookup("zve64d"))
6762  Diag(Loc, diag::err_riscv_type_requires_extension, D) << Ty << "zve64d";
6763  // (ELEN, LMUL) pairs of (8, mf8), (16, mf4), (32, mf2), (64, m1) requires at
6764  // least zve64x
6765  else if (((EltSize == 64 && Info.ElementType->isIntegerType()) ||
6766  MinElts == 1) &&
6767  !FeatureMap.lookup("zve64x"))
6768  Diag(Loc, diag::err_riscv_type_requires_extension, D) << Ty << "zve64x";
6769  else if (Info.ElementType->isFloat16Type() && !FeatureMap.lookup("zvfh") &&
6770  !FeatureMap.lookup("zvfhmin"))
6771  Diag(Loc, diag::err_riscv_type_requires_extension, D)
6772  << Ty << "zvfh or zvfhmin";
6773  else if (Info.ElementType->isBFloat16Type() &&
6774  !FeatureMap.lookup("experimental-zvfbfmin"))
6775  Diag(Loc, diag::err_riscv_type_requires_extension, D) << Ty << "zvfbfmin";
6777  !FeatureMap.lookup("zve32f"))
6778  Diag(Loc, diag::err_riscv_type_requires_extension, D) << Ty << "zve32f";
6779  // Given that caller already checked isRVVType() before calling this function,
6780  // if we don't have at least zve32x supported, then we need to emit error.
6781  else if (!FeatureMap.lookup("zve32x"))
6782  Diag(Loc, diag::err_riscv_type_requires_extension, D) << Ty << "zve32x";
6783 }
6784 
6785 bool Sema::CheckNVPTXBuiltinFunctionCall(const TargetInfo &TI,
6786  unsigned BuiltinID,
6787  CallExpr *TheCall) {
6788  switch (BuiltinID) {
6789  case NVPTX::BI__nvvm_cp_async_ca_shared_global_4:
6790  case NVPTX::BI__nvvm_cp_async_ca_shared_global_8:
6791  case NVPTX::BI__nvvm_cp_async_ca_shared_global_16:
6792  case NVPTX::BI__nvvm_cp_async_cg_shared_global_16:
6793  return checkArgCountAtMost(*this, TheCall, 3);
6794  }
6795 
6796  return false;
6797 }
6798 
6799 // Check if the rounding mode is legal.
6800 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
6801  // Indicates if this instruction has rounding control or just SAE.
6802  bool HasRC = false;
6803 
6804  unsigned ArgNum = 0;
6805  switch (BuiltinID) {
6806  default:
6807  return false;
6808  case X86::BI__builtin_ia32_vcvttsd2si32:
6809  case X86::BI__builtin_ia32_vcvttsd2si64:
6810  case X86::BI__builtin_ia32_vcvttsd2usi32:
6811  case X86::BI__builtin_ia32_vcvttsd2usi64:
6812  case X86::BI__builtin_ia32_vcvttss2si32:
6813  case X86::BI__builtin_ia32_vcvttss2si64:
6814  case X86::BI__builtin_ia32_vcvttss2usi32:
6815  case X86::BI__builtin_ia32_vcvttss2usi64:
6816  case X86::BI__builtin_ia32_vcvttsh2si32:
6817  case X86::BI__builtin_ia32_vcvttsh2si64:
6818  case X86::BI__builtin_ia32_vcvttsh2usi32:
6819  case X86::BI__builtin_ia32_vcvttsh2usi64:
6820  ArgNum = 1;
6821  break;
6822  case X86::BI__builtin_ia32_maxpd512:
6823  case X86::BI__builtin_ia32_maxps512:
6824  case X86::BI__builtin_ia32_minpd512:
6825  case X86::BI__builtin_ia32_minps512:
6826  case X86::BI__builtin_ia32_maxph512:
6827  case X86::BI__builtin_ia32_minph512:
6828  ArgNum = 2;
6829  break;
6830  case X86::BI__builtin_ia32_vcvtph2pd512_mask:
6831  case X86::BI__builtin_ia32_vcvtph2psx512_mask:
6832  case X86::BI__builtin_ia32_cvtps2pd512_mask:
6833  case X86::BI__builtin_ia32_cvttpd2dq512_mask:
6834  case X86::BI__builtin_ia32_cvttpd2qq512_mask:
6835  case X86::BI__builtin_ia32_cvttpd2udq512_mask:
6836  case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
6837  case X86::BI__builtin_ia32_cvttps2dq512_mask:
6838  case X86::BI__builtin_ia32_cvttps2qq512_mask:
6839  case X86::BI__builtin_ia32_cvttps2udq512_mask:
6840  case X86::BI__builtin_ia32_cvttps2uqq512_mask:
6841  case X86::BI__builtin_ia32_vcvttph2w512_mask:
6842  case X86::BI__builtin_ia32_vcvttph2uw512_mask:
6843  case X86::BI__builtin_ia32_vcvttph2dq512_mask:
6844  case X86::BI__builtin_ia32_vcvttph2udq512_mask:
6845  case X86::BI__builtin_ia32_vcvttph2qq512_mask:
6846  case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
6847  case X86::BI__builtin_ia32_exp2pd_mask:
6848  case X86::BI__builtin_ia32_exp2ps_mask:
6849  case X86::BI__builtin_ia32_getexppd512_mask:
6850  case X86::BI__builtin_ia32_getexpps512_mask:
6851  case X86::BI__builtin_ia32_getexpph512_mask:
6852  case X86::BI__builtin_ia32_rcp28pd_mask:
6853  case X86::BI__builtin_ia32_rcp28ps_mask:
6854  case X86::BI__builtin_ia32_rsqrt28pd_mask:
6855  case X86::BI__builtin_ia32_rsqrt28ps_mask:
6856  case X86::BI__builtin_ia32_vcomisd:
6857  case X86::BI__builtin_ia32_vcomiss:
6858  case X86::BI__builtin_ia32_vcomish:
6859  case X86::BI__builtin_ia32_vcvtph2ps512_mask:
6860  ArgNum = 3;
6861  break;
6862  case X86::BI__builtin_ia32_cmppd512_mask:
6863  case X86::BI__builtin_ia32_cmpps512_mask:
6864  case X86::BI__builtin_ia32_cmpsd_mask:
6865  case X86::BI__builtin_ia32_cmpss_mask:
6866  case X86::BI__builtin_ia32_cmpsh_mask:
6867  case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
6868  case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
6869  case X86::BI__builtin_ia32_cvtss2sd_round_mask:
6870  case X86::BI__builtin_ia32_getexpsd128_round_mask:
6871  case X86::BI__builtin_ia32_getexpss128_round_mask:
6872  case X86::BI__builtin_ia32_getexpsh128_round_mask:
6873  case X86::BI__builtin_ia32_getmantpd512_mask:
6874  case X86::BI__builtin_ia32_getmantps512_mask:
6875  case X86::BI__builtin_ia32_getmantph512_mask:
6876  case X86::BI__builtin_ia32_maxsd_round_mask:
6877  case X86::BI__builtin_ia32_maxss_round_mask:
6878  case X86::BI__builtin_ia32_maxsh_round_mask:
6879  case X86::BI__builtin_ia32_minsd_round_mask:
6880  case X86::BI__builtin_ia32_minss_round_mask:
6881  case X86::BI__builtin_ia32_minsh_round_mask:
6882  case X86::BI__builtin_ia32_rcp28sd_round_mask:
6883  case X86::BI__builtin_ia32_rcp28ss_round_mask:
6884  case X86::BI__builtin_ia32_reducepd512_mask:
6885  case X86::BI__builtin_ia32_reduceps512_mask:
6886  case X86::BI__builtin_ia32_reduceph512_mask:
6887  case X86::BI__builtin_ia32_rndscalepd_mask:
6888  case X86::BI__builtin_ia32_rndscaleps_mask:
6889  case X86::BI__builtin_ia32_rndscaleph_mask:
6890  case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
6891  case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
6892  ArgNum = 4;
6893  break;
6894  case X86::BI__builtin_ia32_fixupimmpd512_mask:
6895  case X86::BI__builtin_ia32_fixupimmpd512_maskz:
6896  case X86::BI__builtin_ia32_fixupimmps512_mask:
6897  case X86::BI__builtin_ia32_fixupimmps512_maskz:
6898  case X86::BI__builtin_ia32_fixupimmsd_mask:
6899  case X86::BI__builtin_ia32_fixupimmsd_maskz:
6900  case X86::BI__builtin_ia32_fixupimmss_mask:
6901  case X86::BI__builtin_ia32_fixupimmss_maskz:
6902  case X86::BI__builtin_ia32_getmantsd_round_mask:
6903  case X86::BI__builtin_ia32_getmantss_round_mask:
6904  case X86::BI__builtin_ia32_getmantsh_round_mask:
6905  case X86::BI__builtin_ia32_rangepd512_mask:
6906  case X86::BI__builtin_ia32_rangeps512_mask:
6907  case X86::BI__builtin_ia32_rangesd128_round_mask:
6908  case X86::BI__builtin_ia32_rangess128_round_mask:
6909  case X86::BI__builtin_ia32_reducesd_mask:
6910  case X86::BI__builtin_ia32_reducess_mask:
6911  case X86::BI__builtin_ia32_reducesh_mask:
6912  case X86::BI__builtin_ia32_rndscalesd_round_mask:
6913  case X86::BI__builtin_ia32_rndscaless_round_mask:
6914  case X86::BI__builtin_ia32_rndscalesh_round_mask:
6915  ArgNum = 5;
6916  break;
6917  case X86::BI__builtin_ia32_vcvtsd2si64:
6918  case X86::BI__builtin_ia32_vcvtsd2si32:
6919  case X86::BI__builtin_ia32_vcvtsd2usi32:
6920  case X86::BI__builtin_ia32_vcvtsd2usi64:
6921  case X86::BI__builtin_ia32_vcvtss2si32:
6922  case X86::BI__builtin_ia32_vcvtss2si64:
6923  case X86::BI__builtin_ia32_vcvtss2usi32:
6924  case X86::BI__builtin_ia32_vcvtss2usi64:
6925  case X86::BI__builtin_ia32_vcvtsh2si32:
6926  case X86::BI__builtin_ia32_vcvtsh2si64:
6927  case X86::BI__builtin_ia32_vcvtsh2usi32:
6928  case X86::BI__builtin_ia32_vcvtsh2usi64:
6929  case X86::BI__builtin_ia32_sqrtpd512:
6930  case X86::BI__builtin_ia32_sqrtps512:
6931  case X86::BI__builtin_ia32_sqrtph512:
6932  ArgNum = 1;
6933  HasRC = true;
6934  break;
6935  case X86::BI__builtin_ia32_addph512:
6936  case X86::BI__builtin_ia32_divph512:
6937  case X86::BI__builtin_ia32_mulph512:
6938  case X86::BI__builtin_ia32_subph512:
6939  case X86::BI__builtin_ia32_addpd512:
6940  case X86::BI__builtin_ia32_addps512:
6941  case X86::BI__builtin_ia32_divpd512:
6942  case X86::BI__builtin_ia32_divps512:
6943  case X86::BI__builtin_ia32_mulpd512:
6944  case X86::BI__builtin_ia32_mulps512:
6945  case X86::BI__builtin_ia32_subpd512:
6946  case X86::BI__builtin_ia32_subps512:
6947  case X86::BI__builtin_ia32_cvtsi2sd64:
6948  case X86::BI__builtin_ia32_cvtsi2ss32:
6949  case X86::BI__builtin_ia32_cvtsi2ss64:
6950  case X86::BI__builtin_ia32_cvtusi2sd64:
6951  case X86::BI__builtin_ia32_cvtusi2ss32:
6952  case X86::BI__builtin_ia32_cvtusi2ss64:
6953  case X86::BI__builtin_ia32_vcvtusi2sh:
6954  case X86::BI__builtin_ia32_vcvtusi642sh:
6955  case X86::BI__builtin_ia32_vcvtsi2sh:
6956  case X86::BI__builtin_ia32_vcvtsi642sh:
6957  ArgNum = 2;
6958  HasRC = true;
6959  break;
6960  case X86::BI__builtin_ia32_cvtdq2ps512_mask:
6961  case X86::BI__builtin_ia32_cvtudq2ps512_mask:
6962  case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
6963  case X86::BI__builtin_ia32_vcvtps2phx512_mask:
6964  case X86::BI__builtin_ia32_cvtpd2ps512_mask:
6965  case X86::BI__builtin_ia32_cvtpd2dq512_mask:
6966  case X86::BI__builtin_ia32_cvtpd2qq512_mask:
6967  case X86::BI__builtin_ia32_cvtpd2udq512_mask:
6968  case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
6969  case X86::BI__builtin_ia32_cvtps2dq512_mask:
6970  case X86::BI__builtin_ia32_cvtps2qq512_mask:
6971  case X86::BI__builtin_ia32_cvtps2udq512_mask:
6972  case X86::BI__builtin_ia32_cvtps2uqq512_mask:
6973  case X86::BI__builtin_ia32_cvtqq2pd512_mask:
6974  case X86::BI__builtin_ia32_cvtqq2ps512_mask:
6975  case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
6976  case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
6977  case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
6978  case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
6979  case X86::BI__builtin_ia32_vcvtw2ph512_mask:
6980  case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
6981  case X86::BI__builtin_ia32_vcvtph2w512_mask:
6982  case X86::BI__builtin_ia32_vcvtph2uw512_mask:
6983  case X86::BI__builtin_ia32_vcvtph2dq512_mask:
6984  case X86::BI__builtin_ia32_vcvtph2udq512_mask:
6985  case X86::BI__builtin_ia32_vcvtph2qq512_mask:
6986  case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
6987  case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
6988  case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
6989  ArgNum = 3;
6990  HasRC = true;
6991  break;
6992  case X86::BI__builtin_ia32_addsh_round_mask:
6993  case X86::BI__builtin_ia32_addss_round_mask:
6994  case X86::BI__builtin_ia32_addsd_round_mask:
6995  case X86::BI__builtin_ia32_divsh_round_mask:
6996  case X86::BI__builtin_ia32_divss_round_mask:
6997  case X86::BI__builtin_ia32_divsd_round_mask:
6998  case X86::BI__builtin_ia32_mulsh_round_mask:
6999  case X86::BI__builtin_ia32_mulss_round_mask:
7000  case X86::BI__builtin_ia32_mulsd_round_mask:
7001  case X86::BI__builtin_ia32_subsh_round_mask:
7002  case X86::BI__builtin_ia32_subss_round_mask:
7003  case X86::BI__builtin_ia32_subsd_round_mask:
7004  case X86::BI__builtin_ia32_scalefph512_mask:
7005  case X86::BI__builtin_ia32_scalefpd512_mask:
7006  case X86::BI__builtin_ia32_scalefps512_mask:
7007  case X86::BI__builtin_ia32_scalefsd_round_mask:
7008  case X86::BI__builtin_ia32_scalefss_round_mask:
7009  case X86::BI__builtin_ia32_scalefsh_round_mask:
7010  case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
7011  case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
7012  case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
7013  case X86::BI__builtin_ia32_sqrtsd_round_mask:
7014  case X86::BI__builtin_ia32_sqrtss_round_mask:
7015  case X86::BI__builtin_ia32_sqrtsh_round_mask:
7016  case X86::BI__builtin_ia32_vfmaddsd3_mask:
7017  case X86::BI__builtin_ia32_vfmaddsd3_maskz:
7018  case X86::BI__builtin_ia32_vfmaddsd3_mask3:
7019  case X86::BI__builtin_ia32_vfmaddss3_mask:
7020  case X86::BI__builtin_ia32_vfmaddss3_maskz:
7021  case X86::BI__builtin_ia32_vfmaddss3_mask3:
7022  case X86::BI__builtin_ia32_vfmaddsh3_mask:
7023  case X86::BI__builtin_ia32_vfmaddsh3_maskz:
7024  case X86::BI__builtin_ia32_vfmaddsh3_mask3:
7025  case X86::BI__builtin_ia32_vfmaddpd512_mask:
7026  case X86::BI__builtin_ia32_vfmaddpd512_maskz:
7027  case X86::BI__builtin_ia32_vfmaddpd512_mask3:
7028  case X86::BI__builtin_ia32_vfmsubpd512_mask3:
7029  case X86::BI__builtin_ia32_vfmaddps512_mask:
7030  case X86::BI__builtin_ia32_vfmaddps512_maskz:
7031  case X86::BI__builtin_ia32_vfmaddps512_mask3:
7032  case X86::BI__builtin_ia32_vfmsubps512_mask3:
7033  case X86::BI__builtin_ia32_vfmaddph512_mask:
7034  case X86::BI__builtin_ia32_vfmaddph512_maskz:
7035  case X86::BI__builtin_ia32_vfmaddph512_mask3:
7036  case X86::BI__builtin_ia32_vfmsubph512_mask3:
7037  case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
7038  case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
7039  case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
7040  case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
7041  case X86::BI__builtin_ia32_vfmaddsubps512_mask:
7042  case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
7043  case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
7044  case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
7045  case X86::BI__builtin_ia32_vfmaddsubph512_mask:
7046  case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
7047  case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
7048  case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
7049  case X86::BI__builtin_ia32_vfmaddcsh_mask:
7050  case X86::BI__builtin_ia32_vfmaddcsh_round_mask:
7051  case X86::BI__builtin_ia32_vfmaddcsh_round_mask3:
7052  case X86::BI__builtin_ia32_vfmaddcph512_mask:
7053  case X86::BI__builtin_ia32_vfmaddcph512_maskz:
7054  case X86::BI__builtin_ia32_vfmaddcph512_mask3:
7055  case X86::BI__builtin_ia32_vfcmaddcsh_mask:
7056  case X86::BI__builtin_ia32_vfcmaddcsh_round_mask:
7057  case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3:
7058  case X86::BI__builtin_ia32_vfcmaddcph512_mask:
7059  case X86::BI__builtin_ia32_vfcmaddcph512_maskz:
7060  case X86::BI__builtin_ia32_vfcmaddcph512_mask3:
7061  case X86::BI__builtin_ia32_vfmulcsh_mask:
7062  case X86::BI__builtin_ia32_vfmulcph512_mask:
7063  case X86::BI__builtin_ia32_vfcmulcsh_mask:
7064  case X86::BI__builtin_ia32_vfcmulcph512_mask:
7065  ArgNum = 4;
7066  HasRC = true;
7067  break;
7068  }
7069 
7070  llvm::APSInt Result;
7071 
7072  // We can't check the value of a dependent argument.
7073  Expr *Arg = TheCall->getArg(ArgNum);
7074  if (Arg->isTypeDependent() || Arg->isValueDependent())
7075  return false;
7076 
7077  // Check constant-ness first.
7078  if (BuiltinConstantArg(TheCall, ArgNum, Result))
7079  return true;
7080 
7081  // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
7082  // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
7083  // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
7084  // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
7085  if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
7086  Result == 8/*ROUND_NO_EXC*/ ||
7087  (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
7088  (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
7089  return false;
7090 
7091  return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
7092  << Arg->getSourceRange();
7093 }
7094 
7095 // Check if the gather/scatter scale is legal.
7096 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
7097  CallExpr *TheCall) {
7098  unsigned ArgNum = 0;
7099  switch (BuiltinID) {
7100  default:
7101  return false;
7102  case X86::BI__builtin_ia32_gatherpfdpd:
7103  case X86::BI__builtin_ia32_gatherpfdps:
7104  case X86::BI__builtin_ia32_gatherpfqpd:
7105  case X86::BI__builtin_ia32_gatherpfqps:
7106  case X86::BI__builtin_ia32_scatterpfdpd:
7107  case X86::BI__builtin_ia32_scatterpfdps:
7108  case X86::BI__builtin_ia32_scatterpfqpd:
7109  case X86::BI__builtin_ia32_scatterpfqps:
7110  ArgNum = 3;
7111  break;
7112  case X86::BI__builtin_ia32_gatherd_pd:
7113  case X86::BI__builtin_ia32_gatherd_pd256:
7114  case X86::BI__builtin_ia32_gatherq_pd:
7115  case X86::BI__builtin_ia32_gatherq_pd256:
7116  case X86::BI__builtin_ia32_gatherd_ps:
7117  case X86::BI__builtin_ia32_gatherd_ps256:
7118  case X86::BI__builtin_ia32_gatherq_ps:
7119  case X86::BI__builtin_ia32_gatherq_ps256:
7120  case X86::BI__builtin_ia32_gatherd_q:
7121  case X86::BI__builtin_ia32_gatherd_q256:
7122  case X86::BI__builtin_ia32_gatherq_q:
7123  case X86::BI__builtin_ia32_gatherq_q256:
7124  case X86::BI__builtin_ia32_gatherd_d:
7125  case X86::BI__builtin_ia32_gatherd_d256:
7126  case X86::BI__builtin_ia32_gatherq_d:
7127  case X86::BI__builtin_ia32_gatherq_d256:
7128  case X86::BI__builtin_ia32_gather3div2df:
7129  case X86::BI__builtin_ia32_gather3div2di:
7130  case X86::BI__builtin_ia32_gather3div4df:
7131  case X86::BI__builtin_ia32_gather3div4di:
7132  case X86::BI__builtin_ia32_gather3div4sf:
7133  case X86::BI__builtin_ia32_gather3div4si:
7134  case X86::BI__builtin_ia32_gather3div8sf:
7135  case X86::BI__builtin_ia32_gather3div8si:
7136  case X86::BI__builtin_ia32_gather3siv2df:
7137  case X86::BI__builtin_ia32_gather3siv2di:
7138  case X86::BI__builtin_ia32_gather3siv4df:
7139  case X86::BI__builtin_ia32_gather3siv4di:
7140  case X86::BI__builtin_ia32_gather3siv4sf:
7141  case X86::BI__builtin_ia32_gather3siv4si:
7142  case X86::BI__builtin_ia32_gather3siv8sf:
7143  case X86::BI__builtin_ia32_gather3siv8si:
7144  case X86::BI__builtin_ia32_gathersiv8df:
7145  case X86::BI__builtin_ia32_gathersiv16sf:
7146  case X86::BI__builtin_ia32_gatherdiv8df:
7147  case X86::BI__builtin_ia32_gatherdiv16sf:
7148  case X86::BI__builtin_ia32_gathersiv8di:
7149  case X86::BI__builtin_ia32_gathersiv16si:
7150  case X86::BI__builtin_ia32_gatherdiv8di:
7151  case X86::BI__builtin_ia32_gatherdiv16si:
7152  case X86::BI__builtin_ia32_scatterdiv2df:
7153  case X86::BI__builtin_ia32_scatterdiv2di:
7154  case X86::BI__builtin_ia32_scatterdiv4df:
7155  case X86::BI__builtin_ia32_scatterdiv4di:
7156  case X86::BI__builtin_ia32_scatterdiv4sf:
7157  case X86::BI__builtin_ia32_scatterdiv4si:
7158  case X86::BI__builtin_ia32_scatterdiv8sf:
7159  case X86::BI__builtin_ia32_scatterdiv8si:
7160  case X86::BI__builtin_ia32_scattersiv2df:
7161  case X86::BI__builtin_ia32_scattersiv2di:
7162  case X86::BI__builtin_ia32_scattersiv4df:
7163  case X86::BI__builtin_ia32_scattersiv4di:
7164  case X86::BI__builtin_ia32_scattersiv4sf:
7165  case X86::BI__builtin_ia32_scattersiv4si:
7166  case X86::BI__builtin_ia32_scattersiv8sf:
7167  case X86::BI__builtin_ia32_scattersiv8si:
7168  case X86::BI__builtin_ia32_scattersiv8df:
7169  case X86::BI__builtin_ia32_scattersiv16sf:
7170  case X86::BI__builtin_ia32_scatterdiv8df:
7171  case X86::BI__builtin_ia32_scatterdiv16sf:
7172  case X86::BI__builtin_ia32_scattersiv8di:
7173  case X86::BI__builtin_ia32_scattersiv16si:
7174  case X86::BI__builtin_ia32_scatterdiv8di:
7175  case X86::BI__builtin_ia32_scatterdiv16si:
7176  ArgNum = 4;
7177  break;
7178  }
7179 
7180  llvm::APSInt Result;
7181 
7182  // We can't check the value of a dependent argument.
7183  Expr *Arg = TheCall->getArg(ArgNum);
7184  if (Arg->isTypeDependent() || Arg->isValueDependent())
7185  return false;
7186 
7187  // Check constant-ness first.
7188  if (BuiltinConstantArg(TheCall, ArgNum, Result))
7189  return true;
7190 
7191  if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
7192  return false;
7193 
7194  return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
7195  << Arg->getSourceRange();
7196 }
7197 
7198 enum { TileRegLow = 0, TileRegHigh = 7 };
7199 
7200 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
7201  ArrayRef<int> ArgNums) {
7202  for (int ArgNum : ArgNums) {
7203  if (BuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
7204  return true;
7205  }
7206  return false;
7207 }
7208 
7209 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
7210  ArrayRef<int> ArgNums) {
7211  // Because the max number of tile register is TileRegHigh + 1, so here we use
7212  // each bit to represent the usage of them in bitset.
7213  std::bitset<TileRegHigh + 1> ArgValues;
7214  for (int ArgNum : ArgNums) {
7215  Expr *Arg = TheCall->getArg(ArgNum);
7216  if (Arg->isTypeDependent() || Arg->isValueDependent())
7217  continue;
7218 
7219  llvm::APSInt Result;
7220  if (BuiltinConstantArg(TheCall, ArgNum, Result))
7221  return true;
7222  int ArgExtValue = Result.getExtValue();
7223  assert((ArgExtValue >= TileRegLow && ArgExtValue <= TileRegHigh) &&
7224  "Incorrect tile register num.");
7225  if (ArgValues.test(ArgExtValue))
7226  return Diag(TheCall->getBeginLoc(),
7227  diag::err_x86_builtin_tile_arg_duplicate)
7228  << TheCall->getArg(ArgNum)->getSourceRange();
7229  ArgValues.set(ArgExtValue);
7230  }
7231  return false;
7232 }
7233 
7234 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
7235  ArrayRef<int> ArgNums) {
7236  return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
7237  CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
7238 }
7239 
7240 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
7241  switch (BuiltinID) {
7242  default:
7243  return false;
7244  case X86::BI__builtin_ia32_tileloadd64:
7245  case X86::BI__builtin_ia32_tileloaddt164:
7246  case X86::BI__builtin_ia32_tilestored64:
7247  case X86::BI__builtin_ia32_tilezero:
7248  return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
7249  case X86::BI__builtin_ia32_tdpbssd:
7250  case X86::BI__builtin_ia32_tdpbsud:
7251  case X86::BI__builtin_ia32_tdpbusd:
7252  case X86::BI__builtin_ia32_tdpbuud:
7253  case X86::BI__builtin_ia32_tdpbf16ps:
7254  case X86::BI__builtin_ia32_tdpfp16ps:
7255  case X86::BI__builtin_ia32_tcmmimfp16ps:
7256  case X86::BI__builtin_ia32_tcmmrlfp16ps:
7257  return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
7258  }
7259 }
7260 static bool isX86_32Builtin(unsigned BuiltinID) {
7261  // These builtins only work on x86-32 targets.
7262  switch (BuiltinID) {
7263  case X86::BI__builtin_ia32_readeflags_u32:
7264  case X86::BI__builtin_ia32_writeeflags_u32:
7265  return true;
7266  }
7267 
7268  return false;
7269 }
7270 
7271 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
7272  CallExpr *TheCall) {
7273  // Check for 32-bit only builtins on a 64-bit target.
7274  const llvm::Triple &TT = TI.getTriple();
7275  if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
7276  return Diag(TheCall->getCallee()->getBeginLoc(),
7277  diag::err_32_bit_builtin_64_bit_tgt);
7278 
7279  // If the intrinsic has rounding or SAE make sure its valid.
7280  if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
7281  return true;
7282 
7283  // If the intrinsic has a gather/scatter scale immediate make sure its valid.
7284  if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
7285  return true;
7286 
7287  // If the intrinsic has a tile arguments, make sure they are valid.
7288  if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
7289  return true;
7290 
7291  // For intrinsics which take an immediate value as part of the instruction,
7292  // range check them here.
7293  int i = 0, l = 0, u = 0;
7294  switch (BuiltinID) {
7295  default:
7296  return false;
7297  case X86::BI__builtin_ia32_vec_ext_v2si:
7298  case X86::BI__builtin_ia32_vec_ext_v2di:
7299  case X86::BI__builtin_ia32_vextractf128_pd256:
7300  case X86::BI__builtin_ia32_vextractf128_ps256:
7301  case X86::BI__builtin_ia32_vextractf128_si256:
7302  case X86::BI__builtin_ia32_extract128i256:
7303  case X86::BI__builtin_ia32_extractf64x4_mask:
7304  case X86::BI__builtin_ia32_extracti64x4_mask:
7305  case X86::BI__builtin_ia32_extractf32x8_mask:
7306  case X86::BI__builtin_ia32_extracti32x8_mask:
7307  case X86::BI__builtin_ia32_extractf64x2_256_mask:
7308  case X86::BI__builtin_ia32_extracti64x2_256_mask:
7309  case X86::BI__builtin_ia32_extractf32x4_256_mask:
7310  case X86::BI__builtin_ia32_extracti32x4_256_mask:
7311  i = 1; l = 0; u = 1;
7312  break;
7313  case X86::BI__builtin_ia32_vec_set_v2di:
7314  case X86::BI__builtin_ia32_vinsertf128_pd256:
7315  case X86::BI__builtin_ia32_vinsertf128_ps256:
7316  case X86::BI__builtin_ia32_vinsertf128_si256:
7317  case X86::BI__builtin_ia32_insert128i256:
7318  case X86::BI__builtin_ia32_insertf32x8:
7319  case X86::BI__builtin_ia32_inserti32x8:
7320  case X86::BI__builtin_ia32_insertf64x4:
7321  case X86::BI__builtin_ia32_inserti64x4:
7322  case X86::BI__builtin_ia32_insertf64x2_256:
7323  case X86::BI__builtin_ia32_inserti64x2_256:
7324  case X86::BI__builtin_ia32_insertf32x4_256:
7325  case X86::BI__builtin_ia32_inserti32x4_256:
7326  i = 2; l = 0; u = 1;
7327  break;
7328  case X86::BI__builtin_ia32_vpermilpd:
7329  case X86::BI__builtin_ia32_vec_ext_v4hi:
7330  case X86::BI__builtin_ia32_vec_ext_v4si:
7331  case X86::BI__builtin_ia32_vec_ext_v4sf:
7332  case X86::BI__builtin_ia32_vec_ext_v4di:
7333  case X86::BI__builtin_ia32_extractf32x4_mask:
7334  case X86::BI__builtin_ia32_extracti32x4_mask:
7335  case X86::BI__builtin_ia32_extractf64x2_512_mask:
7336  case X86::BI__builtin_ia32_extracti64x2_512_mask:
7337  i = 1; l = 0; u = 3;
7338  break;
7339  case X86::BI_mm_prefetch:
7340  case X86::BI__builtin_ia32_vec_ext_v8hi:
7341  case X86::BI__builtin_ia32_vec_ext_v8si:
7342  i = 1; l = 0; u = 7;
7343  break;
7344  case X86::BI__builtin_ia32_sha1rnds4:
7345  case X86::BI__builtin_ia32_blendpd:
7346  case X86::BI__builtin_ia32_shufpd:
7347  case X86::BI__builtin_ia32_vec_set_v4hi:
7348  case X86::BI__builtin_ia32_vec_set_v4si:
7349  case X86::BI__builtin_ia32_vec_set_v4di:
7350  case X86::BI__builtin_ia32_shuf_f32x4_256:
7351  case X86::BI__builtin_ia32_shuf_f64x2_256:
7352  case X86::BI__builtin_ia32_shuf_i32x4_256:
7353  case X86::BI__builtin_ia32_shuf_i64x2_256:
7354  case X86::BI__builtin_ia32_insertf64x2_512:
7355  case X86::BI__builtin_ia32_inserti64x2_512:
7356  case X86::BI__builtin_ia32_insertf32x4:
7357  case X86::BI__builtin_ia32_inserti32x4:
7358  i = 2; l = 0; u = 3;
7359  break;
7360  case X86::BI__builtin_ia32_vpermil2pd:
7361  case X86::BI__builtin_ia32_vpermil2pd256:
7362  case X86::BI__builtin_ia32_vpermil2ps:
7363  case X86::BI__builtin_ia32_vpermil2ps256:
7364  i = 3; l = 0; u = 3;
7365  break;
7366  case X86::BI__builtin_ia32_cmpb128_mask:
7367  case X86::BI__builtin_ia32_cmpw128_mask:
7368  case X86::BI__builtin_ia32_cmpd128_mask:
7369  case X86::BI__builtin_ia32_cmpq128_mask:
7370  case X86::BI__builtin_ia32_cmpb256_mask:
7371  case X86::BI__builtin_ia32_cmpw256_mask:
7372  case X86::BI__builtin_ia32_cmpd256_mask:
7373  case X86::BI__builtin_ia32_cmpq256_mask:
7374  case X86::BI__builtin_ia32_cmpb512_mask:
7375  case X86::BI__builtin_ia32_cmpw512_mask:
7376  case X86::BI__builtin_ia32_cmpd512_mask:
7377  case X86::BI__builtin_ia32_cmpq512_mask:
7378  case X86::BI__builtin_ia32_ucmpb128_mask:
7379  case X86::BI__builtin_ia32_ucmpw128_mask:
7380  case X86::BI__builtin_ia32_ucmpd128_mask:
7381  case X86::BI__builtin_ia32_ucmpq128_mask:
7382  case X86::BI__builtin_ia32_ucmpb256_mask:
7383  case X86::BI__builtin_ia32_ucmpw256_mask:
7384  case X86::BI__builtin_ia32_ucmpd256_mask:
7385  case X86::BI__builtin_ia32_ucmpq256_mask:
7386  case X86::BI__builtin_ia32_ucmpb512_mask:
7387  case X86::BI__builtin_ia32_ucmpw512_mask:
7388  case X86::BI__builtin_ia32_ucmpd512_mask:
7389  case X86::BI__builtin_ia32_ucmpq512_mask:
7390  case X86::BI__builtin_ia32_vpcomub:
7391  case X86::BI__builtin_ia32_vpcomuw:
7392  case X86::BI__builtin_ia32_vpcomud:
7393  case X86::BI__builtin_ia32_vpcomuq:
7394  case X86::BI__builtin_ia32_vpcomb:
7395  case X86::BI__builtin_ia32_vpcomw:
7396  case X86::BI__builtin_ia32_vpcomd:
7397  case X86::BI__builtin_ia32_vpcomq:
7398  case X86::BI__builtin_ia32_vec_set_v8hi:
7399  case X86::BI__builtin_ia32_vec_set_v8si:
7400  i = 2; l = 0; u = 7;
7401  break;
7402  case X86::BI__builtin_ia32_vpermilpd256:
7403  case X86::BI__builtin_ia32_roundps:
7404  case X86::BI__builtin_ia32_roundpd:
7405  case X86::BI__builtin_ia32_roundps256:
7406  case X86::BI__builtin_ia32_roundpd256:
7407  case X86::BI__builtin_ia32_getmantpd128_mask:
7408  case X86::BI__builtin_ia32_getmantpd256_mask:
7409  case X86::BI__builtin_ia32_getmantps128_mask:
7410  case X86::BI__builtin_ia32_getmantps256_mask:
7411  case X86::BI__builtin_ia32_getmantpd512_mask:
7412  case X86::BI__builtin_ia32_getmantps512_mask:
7413  case X86::BI__builtin_ia32_getmantph128_mask:
7414  case X86::BI__builtin_ia32_getmantph256_mask:
7415  case X86::BI__builtin_ia32_getmantph512_mask:
7416  case X86::BI__builtin_ia32_vec_ext_v16qi:
7417  case X86::BI__builtin_ia32_vec_ext_v16hi:
7418  i = 1; l = 0; u = 15;
7419  break;
7420  case X86::BI__builtin_ia32_pblendd128:
7421  case X86::BI__builtin_ia32_blendps:
7422  case X86::BI__builtin_ia32_blendpd256:
7423  case X86::BI__builtin_ia32_shufpd256:
7424  case X86::BI__builtin_ia32_roundss:
7425  case X86::BI__builtin_ia32_roundsd:
7426  case X86::BI__builtin_ia32_rangepd128_mask:
7427  case X86::BI__builtin_ia32_rangepd256_mask:
7428  case X86::BI__builtin_ia32_rangepd512_mask:
7429  case X86::BI__builtin_ia32_rangeps128_mask:
7430  case X86::BI__builtin_ia32_rangeps256_mask:
7431  case X86::BI__builtin_ia32_rangeps512_mask:
7432  case X86::BI__builtin_ia32_getmantsd_round_mask:
7433  case X86::BI__builtin_ia32_getmantss_round_mask:
7434  case X86::BI__builtin_ia32_getmantsh_round_mask:
7435  case X86::BI__builtin_ia32_vec_set_v16qi:
7436  case X86::BI__builtin_ia32_vec_set_v16hi:
7437  i = 2; l = 0; u = 15;
7438  break;
7439  case X86::BI__builtin_ia32_vec_ext_v32qi:
7440  i = 1; l = 0; u = 31;
7441  break;
7442  case X86::BI__builtin_ia32_cmpps:
7443  case X86::BI__builtin_ia32_cmpss:
7444  case X86::BI__builtin_ia32_cmppd:
7445  case X86::BI__builtin_ia32_cmpsd:
7446  case X86::BI__builtin_ia32_cmpps256:
7447  case X86::BI__builtin_ia32_cmppd256:
7448  case X86::BI__builtin_ia32_cmpps128_mask:
7449  case X86::BI__builtin_ia32_cmppd128_mask:
7450  case X86::BI__builtin_ia32_cmpps256_mask:
7451  case X86::BI__builtin_ia32_cmppd256_mask:
7452  case X86::BI__builtin_ia32_cmpps512_mask:
7453  case X86::BI__builtin_ia32_cmppd512_mask:
7454  case X86::BI__builtin_ia32_cmpsd_mask:
7455  case X86::BI__builtin_ia32_cmpss_mask:
7456  case X86::BI__builtin_ia32_vec_set_v32qi:
7457  i = 2; l = 0; u = 31;
7458  break;
7459  case X86::BI__builtin_ia32_permdf256:
7460  case X86::BI__builtin_ia32_permdi256:
7461  case X86::BI__builtin_ia32_permdf512:
7462  case X86::BI__builtin_ia32_permdi512:
7463  case X86::BI__builtin_ia32_vpermilps:
7464  case X86::BI__builtin_ia32_vpermilps256:
7465  case X86::BI__builtin_ia32_vpermilpd512:
7466  case X86::BI__builtin_ia32_vpermilps512:
7467  case X86::BI__builtin_ia32_pshufd:
7468  case X86::BI__builtin_ia32_pshufd256:
7469  case X86::BI__builtin_ia32_pshufd512:
7470  case X86::BI__builtin_ia32_pshufhw:
7471  case X86::BI__builtin_ia32_pshufhw256:
7472  case X86::BI__builtin_ia32_pshufhw512:
7473  case X86::BI__builtin_ia32_pshuflw:
7474  case X86::BI__builtin_ia32_pshuflw256:
7475  case X86::BI__builtin_ia32_pshuflw512:
7476  case X86::BI__builtin_ia32_vcvtps2ph:
7477  case X86::BI__builtin_ia32_vcvtps2ph_mask:
7478  case X86::BI__builtin_ia32_vcvtps2ph256:
7479  case X86::BI__builtin_ia32_vcvtps2ph256_mask:
7480  case X86::BI__builtin_ia32_vcvtps2ph512_mask:
7481  case X86::BI__builtin_ia32_rndscaleps_128_mask:
7482  case X86::BI__builtin_ia32_rndscalepd_128_mask:
7483  case X86::BI__builtin_ia32_rndscaleps_256_mask:
7484  case X86::BI__builtin_ia32_rndscalepd_256_mask:
7485  case X86::BI__builtin_ia32_rndscaleps_mask:
7486  case X86::BI__builtin_ia32_rndscalepd_mask:
7487  case X86::BI__builtin_ia32_rndscaleph_mask:
7488  case X86::BI__builtin_ia32_reducepd128_mask:
7489  case X86::BI__builtin_ia32_reducepd256_mask:
7490  case X86::BI__builtin_ia32_reducepd512_mask:
7491  case X86::BI__builtin_ia32_reduceps128_mask:
7492  case X86::BI__builtin_ia32_reduceps256_mask:
7493  case X86::BI__builtin_ia32_reduceps512_mask:
7494  case X86::BI__builtin_ia32_reduceph128_mask:
7495  case X86::BI__builtin_ia32_reduceph256_mask:
7496  case X86::BI__builtin_ia32_reduceph512_mask:
7497  case X86::BI__builtin_ia32_prold512:
7498  case X86::BI__builtin_ia32_prolq512:
7499  case X86::BI__builtin_ia32_prold128:
7500  case X86::BI__builtin_ia32_prold256:
7501  case X86::BI__builtin_ia32_prolq128:
7502  case X86::BI__builtin_ia32_prolq256:
7503  case X86::BI__builtin_ia32_prord512:
7504  case X86::BI__builtin_ia32_prorq512:
7505  case X86::BI__builtin_ia32_prord128:
7506  case X86::BI__builtin_ia32_prord256:
7507  case X86::BI__builtin_ia32_prorq128:
7508  case X86::BI__builtin_ia32_prorq256:
7509  case X86::BI__builtin_ia32_fpclasspd128_mask:
7510  case X86::BI__builtin_ia32_fpclasspd256_mask:
7511  case X86::BI__builtin_ia32_fpclassps128_mask:
7512  case X86::BI__builtin_ia32_fpclassps256_mask:
7513  case X86::BI__builtin_ia32_fpclassps512_mask:
7514  case X86::BI__builtin_ia32_fpclasspd512_mask:
7515  case X86::BI__builtin_ia32_fpclassph128_mask:
7516  case X86::BI__builtin_ia32_fpclassph256_mask:
7517  case X86::BI__builtin_ia32_fpclassph512_mask:
7518  case X86::BI__builtin_ia32_fpclasssd_mask:
7519  case X86::BI__builtin_ia32_fpclassss_mask:
7520  case X86::BI__builtin_ia32_fpclasssh_mask:
7521  case X86::BI__builtin_ia32_pslldqi128_byteshift:
7522  case X86::BI__builtin_ia32_pslldqi256_byteshift:
7523  case X86::BI__builtin_ia32_pslldqi512_byteshift:
7524  case X86::BI__builtin_ia32_psrldqi128_byteshift:
7525  case X86::BI__builtin_ia32_psrldqi256_byteshift:
7526  case X86::BI__builtin_ia32_psrldqi512_byteshift:
7527  case X86::BI__builtin_ia32_kshiftliqi:
7528  case X86::BI__builtin_ia32_kshiftlihi:
7529  case X86::BI__builtin_ia32_kshiftlisi:
7530  case X86::BI__builtin_ia32_kshiftlidi:
7531  case X86::BI__builtin_ia32_kshiftriqi:
7532  case X86::BI__builtin_ia32_kshiftrihi:
7533  case X86::BI__builtin_ia32_kshiftrisi:
7534  case X86::BI__builtin_ia32_kshiftridi:
7535  i = 1; l = 0; u = 255;
7536  break;
7537  case X86::BI__builtin_ia32_vperm2f128_pd256:
7538  case X86::BI__builtin_ia32_vperm2f128_ps256:
7539  case X86::BI__builtin_ia32_vperm2f128_si256:
7540  case X86::BI__builtin_ia32_permti256:
7541  case X86::BI__builtin_ia32_pblendw128:
7542  case X86::BI__builtin_ia32_pblendw256:
7543  case X86::BI__builtin_ia32_blendps256:
7544  case X86::BI__builtin_ia32_pblendd256:
7545  case X86::BI__builtin_ia32_palignr128:
7546  case X86::BI__builtin_ia32_palignr256:
7547  case X86::BI__builtin_ia32_palignr512:
7548  case X86::BI__builtin_ia32_alignq512:
7549  case X86::BI__builtin_ia32_alignd512:
7550  case X86::BI__builtin_ia32_alignd128:
7551  case X86::BI__builtin_ia32_alignd256:
7552  case X86::BI__builtin_ia32_alignq128:
7553  case X86::BI__builtin_ia32_alignq256:
7554  case X86::BI__builtin_ia32_vcomisd:
7555  case X86::BI__builtin_ia32_vcomiss:
7556  case X86::BI__builtin_ia32_shuf_f32x4:
7557  case X86::BI__builtin_ia32_shuf_f64x2:
7558  case X86::BI__builtin_ia32_shuf_i32x4:
7559  case X86::BI__builtin_ia32_shuf_i64x2:
7560  case X86::BI__builtin_ia32_shufpd512:
7561  case X86::BI__builtin_ia32_shufps:
7562  case X86::BI__builtin_ia32_shufps256:
7563  case X86::BI__builtin_ia32_shufps512:
7564  case X86::BI__builtin_ia32_dbpsadbw128:
7565  case X86::BI__builtin_ia32_dbpsadbw256:
7566  case X86::BI__builtin_ia32_dbpsadbw512:
7567  case X86::BI__builtin_ia32_vpshldd128:
7568  case X86::BI__builtin_ia32_vpshldd256:
7569  case X86::BI__builtin_ia32_vpshldd512:
7570  case X86::BI__builtin_ia32_vpshldq128:
7571  case X86::BI__builtin_ia32_vpshldq256:
7572  case X86::BI__builtin_ia32_vpshldq512:
7573  case X86::BI__builtin_ia32_vpshldw128:
7574  case X86::BI__builtin_ia32_vpshldw256:
7575  case X86::BI__builtin_ia32_vpshldw512:
7576  case X86::BI__builtin_ia32_vpshrdd128:
7577  case X86::BI__builtin_ia32_vpshrdd256:
7578  case X86::BI__builtin_ia32_vpshrdd512:
7579  case X86::BI__builtin_ia32_vpshrdq128:
7580  case X86::BI__builtin_ia32_vpshrdq256:
7581  case X86::BI__builtin_ia32_vpshrdq512:
7582  case X86::BI__builtin_ia32_vpshrdw128:
7583  case X86::BI__builtin_ia32_vpshrdw256:
7584  case X86::BI__builtin_ia32_vpshrdw512:
7585  i = 2; l = 0; u = 255;
7586  break;
7587  case X86::BI__builtin_ia32_fixupimmpd512_mask:
7588  case X86::BI__builtin_ia32_fixupimmpd512_maskz:
7589  case X86::BI__builtin_ia32_fixupimmps512_mask:
7590  case X86::BI__builtin_ia32_fixupimmps512_maskz:
7591  case X86::BI__builtin_ia32_fixupimmsd_mask:
7592  case X86::BI__builtin_ia32_fixupimmsd_maskz:
7593  case X86::BI__builtin_ia32_fixupimmss_mask:
7594  case X86::BI__builtin_ia32_fixupimmss_maskz:
7595  case X86::BI__builtin_ia32_fixupimmpd128_mask:
7596  case X86::BI__builtin_ia32_fixupimmpd128_maskz:
7597  case X86::BI__builtin_ia32_fixupimmpd256_mask:
7598  case X86::BI__builtin_ia32_fixupimmpd256_maskz:
7599  case X86::BI__builtin_ia32_fixupimmps128_mask:
7600  case X86::BI__builtin_ia32_fixupimmps128_maskz:
7601  case X86::BI__builtin_ia32_fixupimmps256_mask:
7602  case X86::BI__builtin_ia32_fixupimmps256_maskz:
7603  case X86::BI__builtin_ia32_pternlogd512_mask:
7604  case X86::BI__builtin_ia32_pternlogd512_maskz:
7605  case X86::BI__builtin_ia32_pternlogq512_mask:
7606  case X86::BI__builtin_ia32_pternlogq512_maskz:
7607  case X86::BI__builtin_ia32_pternlogd128_mask:
7608  case X86::BI__builtin_ia32_pternlogd128_maskz:
7609  case X86::BI__builtin_ia32_pternlogd256_mask:
7610  case X86::BI__builtin_ia32_pternlogd256_maskz:
7611  case X86::BI__builtin_ia32_pternlogq128_mask:
7612  case X86::BI__builtin_ia32_pternlogq128_maskz:
7613  case X86::BI__builtin_ia32_pternlogq256_mask:
7614  case X86::BI__builtin_ia32_pternlogq256_maskz:
7615  case X86::BI__builtin_ia32_vsm3rnds2:
7616  i = 3; l = 0; u = 255;
7617  break;
7618  case X86::BI__builtin_ia32_gatherpfdpd:
7619  case X86::BI__builtin_ia32_gatherpfdps:
7620  case X86::BI__builtin_ia32_gatherpfqpd:
7621  case X86::BI__builtin_ia32_gatherpfqps:
7622  case X86::BI__builtin_ia32_scatterpfdpd:
7623  case X86::BI__builtin_ia32_scatterpfdps:
7624  case X86::BI__builtin_ia32_scatterpfqpd:
7625  case X86::BI__builtin_ia32_scatterpfqps:
7626  i = 4; l = 2; u = 3;
7627  break;
7628  case X86::BI__builtin_ia32_reducesd_mask:
7629  case X86::BI__builtin_ia32_reducess_mask:
7630  case X86::BI__builtin_ia32_rndscalesd_round_mask:
7631  case X86::BI__builtin_ia32_rndscaless_round_mask:
7632  case X86::BI__builtin_ia32_rndscalesh_round_mask:
7633  case X86::BI__builtin_ia32_reducesh_mask:
7634  i = 4; l = 0; u = 255;
7635  break;
7636  case X86::BI__builtin_ia32_cmpccxadd32:
7637  case X86::BI__builtin_ia32_cmpccxadd64:
7638  i = 3; l = 0; u = 15;
7639  break;
7640  }
7641 
7642  // Note that we don't force a hard error on the range check here, allowing
7643  // template-generated or macro-generated dead code to potentially have out-of-
7644  // range values. These need to code generate, but don't need to necessarily
7645  // make any sense. We use a warning that defaults to an error.
7646  return BuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
7647 }
7648 
7649 static bool checkIntelFPGARegArgument(Sema &S, QualType ArgType,
7650  SourceLocation &Loc) {
7651  if (ArgType.getTypePtr()->isArrayType())
7652  return true;
7653 
7654  // Non-POD classes are allowed. Each field is checked for illegal type.
7655  if (CXXRecordDecl *Record = ArgType->getAsCXXRecordDecl()) {
7656  for (auto *FD : Record->fields()) {
7657  QualType T = FD->getType();
7658  Loc = FD->getLocation();
7659  if (const ArrayType *AT = T->getAsArrayTypeUnsafe())
7660  T = AT->getElementType();
7661  if (checkIntelFPGARegArgument(S, T, Loc))
7662  return true;
7663  }
7664  return false;
7665  }
7666 
7667  QualType CTy = ArgType.getCanonicalType();
7668 
7669  if (CTy->isFunctionPointerType() || CTy->isImageType() ||
7670  CTy->isEventT() || CTy->isSamplerT() || CTy->isPipeType())
7671  return true;
7672 
7673  // Check to filter out unintended types. Records are handled above.
7674  if (!CTy.isCXX98PODType(S.Context))
7675  return true;
7676 
7677  return false;
7678 }
7679 
7680 bool Sema::CheckIntelFPGARegBuiltinFunctionCall(unsigned BuiltinID,
7681  CallExpr *TheCall) {
7682  switch (BuiltinID) {
7683  case Builtin::BI__builtin_intel_fpga_reg: {
7684  if (checkArgCount(*this, TheCall, 1))
7685  return true;
7686 
7687  Expr *Arg = TheCall->getArg(0);
7688  QualType ArgType = Arg->getType();
7689  SourceLocation Loc;
7690 
7691  if (checkIntelFPGARegArgument(*this, ArgType, Loc)) {
7692  Diag(TheCall->getBeginLoc(), diag::err_intel_fpga_reg_limitations)
7693  << (ArgType.getTypePtr()->isRecordType() ? 1 : 0) << ArgType
7694  << TheCall->getSourceRange();
7695  if (ArgType.getTypePtr()->isRecordType())
7696  Diag(Loc, diag::illegal_type_declared_here);
7697  return true;
7698  }
7699 
7700  TheCall->setType(ArgType);
7701 
7702  return false;
7703  }
7704  default:
7705  return true;
7706  }
7707 }
7708 
7709 bool Sema::CheckIntelFPGAMemBuiltinFunctionCall(CallExpr *TheCall) {
7710  const unsigned MinNumArgs = 3;
7711  const unsigned MaxNumArgs = 7;
7712  unsigned NumArgs = TheCall->getNumArgs();
7713 
7714  // Make sure we have the minimum number of provided arguments.
7715  if (checkArgCountAtLeast(*this, TheCall, MinNumArgs))
7716  return true;
7717 
7718  // Make sure we don't have too many arguments.
7719  if (checkArgCountAtMost(*this, TheCall, MaxNumArgs))
7720  return true;
7721 
7722  Expr *PointerArg = TheCall->getArg(0);
7723  QualType PointerArgType = PointerArg->getType();
7724 
7725  // Make sure that the first argument is a pointer
7726  if (!isa<PointerType>(PointerArgType))
7727  return Diag(PointerArg->getBeginLoc(),
7728  diag::err_intel_fpga_mem_arg_mismatch)
7729  << 0;
7730 
7731  // Make sure that the pointer points to a legal type
7732  // We use the same argument checks used for __builtin_intel_fpga_reg
7733  QualType PointeeType = PointerArgType->getPointeeType();
7734  SourceLocation Loc;
7735  if (checkIntelFPGARegArgument(*this, PointeeType, Loc)) {
7736  Diag(TheCall->getBeginLoc(), diag::err_intel_fpga_mem_limitations)
7737  << (PointeeType->isRecordType() ? 1 : 0) << PointerArgType
7738  << TheCall->getSourceRange();
7739  if (PointeeType->isRecordType())
7740  Diag(Loc, diag::illegal_type_declared_here);
7741  return true;
7742  }
7743 
7744  // Second argument must be a constant integer
7745  llvm::APSInt Result;
7746  if (BuiltinConstantArg(TheCall, 1, Result))
7747  return true;
7748 
7749  // Third argument (CacheSize) must be a non-negative constant integer
7750  if (BuiltinConstantArg(TheCall, 2, Result))
7751  return true;
7752  if (Result < 0)
7753  return Diag(TheCall->getArg(2)->getBeginLoc(),
7754  diag::err_intel_fpga_mem_arg_mismatch) << 1;
7755 
7756  // The last four optional arguments must be signed constant integers.
7757  for (unsigned I = MinNumArgs; I != NumArgs; ++I) {
7758  if (BuiltinConstantArg(TheCall, I, Result))
7759  return true;
7760  }
7761 
7762  // Set the return type to be the same as the type of the first argument
7763  // (pointer argument)
7764  TheCall->setType(PointerArgType);
7765  return false;
7766 }
7767 
7768 bool Sema::CheckIntelSYCLPtrAnnotationBuiltinFunctionCall(unsigned BuiltinID,
7769  CallExpr *TheCall) {
7770  unsigned NumArgs = TheCall->getNumArgs();
7771  // Make sure we have the minimum number of provided arguments.
7772  if (checkArgCountAtLeast(*this, TheCall, 1)) {
7773  return true;
7774  }
7775 
7776  // Make sure we have odd number of arguments.
7777  if (!(NumArgs & 0x1)) {
7778  return Diag(TheCall->getEndLoc(),
7779  diag::err_intel_sycl_ptr_annotation_arg_number_mismatch);
7780  }
7781 
7782  // First argument should be a pointer.
7783  Expr *PointerArg = TheCall->getArg(0);
7784  QualType PointerArgType = PointerArg->getType();
7785 
7786  if (!isa<PointerType>(PointerArgType))
7787  return Diag(PointerArg->getBeginLoc(),
7788  diag::err_intel_sycl_ptr_annotation_mismatch)
7789  << 0;
7790 
7791  // Following arguments are paired in format ("String", integer).
7792  unsigned I = 1;
7793  for (; I <= NumArgs / 2; ++I) {
7794  // must be string Literal/const char*
7795  auto Arg = TheCall->getArg(I)->IgnoreParenImpCasts();
7796  Expr::EvalResult Result;
7797  if (!isa<StringLiteral>(Arg) &&
7798  !maybeConstEvalStringLiteral(this->Context, Arg)) {
7799  Diag(TheCall->getArg(I)->getBeginLoc(),
7800  diag::err_intel_sycl_ptr_annotation_mismatch)
7801  << 1;
7802  return true;
7803  }
7804  }
7805 
7806  llvm::APSInt Result;
7807  for (; I != NumArgs; ++I) {
7808  // must be integer
7809  if (BuiltinConstantArg(TheCall, I, Result))
7810  return true;
7811  }
7812 
7813  // Set the return type to be the same as the type of the first argument
7814  TheCall->setType(PointerArgType);
7815  return false;
7816 }
7817 
7819  const VarDecl *VD) {
7820  assert(VD && "Expecting valid declaration");
7821  APValue *SpecializationId = VD->evaluateValue();
7822  assert(SpecializationId && "Expecting a non-null SpecializationId");
7823  assert(SpecializationId->getKind() == APValue::ValueKind::Struct &&
7824  "Expecting SpecializationId to be of kind Struct");
7825  assert(SpecializationId->getStructNumFields() == 1 &&
7826  "Expecting SpecializationId to have a single field for the default "
7827  "value");
7828  APValue Default = SpecializationId->getStructField(0);
7829  assert(Default.isInt() && "Expecting the default value to be an integer");
7830  return Default.getInt();
7831 }
7832 
7833 bool Sema::CheckIntelSYCLAllocaBuiltinFunctionCall(unsigned BuiltinID,
7834  CallExpr *Call) {
7835  assert(getLangOpts().SYCLIsDevice &&
7836  "Builtin can only be used in SYCL device code");
7837 
7838  assert((BuiltinID == Builtin::BI__builtin_intel_sycl_alloca ||
7839  BuiltinID == Builtin::BI__builtin_intel_sycl_alloca_with_align) &&
7840  "Unexpected builtin");
7841 
7842  bool IsAlignedAlloca =
7843  BuiltinID == Builtin::BI__builtin_intel_sycl_alloca_with_align;
7844 
7845  constexpr unsigned InvalidIndex = -1;
7846  constexpr unsigned ElementTypeIndex = 0;
7847  const unsigned AlignmentIndex = IsAlignedAlloca ? 1 : InvalidIndex;
7848  const unsigned SpecNameIndex = IsAlignedAlloca ? 2 : 1;
7849 
7850  SourceLocation Loc = Call->getBeginLoc();
7851 
7852  // This builtin cannot be called directly. As it needs to pass template
7853  // arguments, this is always an alias.
7854  const FunctionDecl *FD = Call->getDirectCallee();
7855  assert(FD && "Builtin cannot be called from a function pointer");
7856  if (!FD->hasAttr<BuiltinAliasAttr>()) {
7857  Diag(Loc, diag::err_intel_sycl_alloca_no_alias) << IsAlignedAlloca;
7858  return true;
7859  }
7860 
7861  // Check a single argument is passed
7862  if (checkArgCount(*this, Call, 1))
7863  return true;
7864 
7865  // Check three template arguments are passed
7866  unsigned DesiredTemplateArgumentsCount = IsAlignedAlloca ? 4 : 3;
7868  if (!CST || CST->size() != DesiredTemplateArgumentsCount) {
7869  Diag(Loc, diag::err_intel_sycl_alloca_wrong_template_arg_count)
7870  << IsAlignedAlloca << (CST ? CST->size() : 0);
7871  return true;
7872  }
7873 
7874  // Check the single argument is of type `sycl::kernel_handler &`
7875  constexpr auto CheckArg = [](QualType Ty) {
7876  if (!Ty->isLValueReferenceType())
7877  return true;
7878  Ty = Ty->getPointeeType();
7879  return !(Ty.getQualifiers().empty() &&
7880  SemaSYCL::isSyclType(Ty, SYCLTypeAttr::kernel_handler));
7881  };
7882  if (CheckArg(FD->getParamDecl(0)->getType())) {
7883  Diag(Loc, diag::err_intel_sycl_alloca_wrong_arg)
7884  << IsAlignedAlloca << FD->getParamDecl(0)->getType();
7885  return true;
7886  }
7887 
7888  // Check the return type is `sycl::multi_ptr<ET,
7889  // sycl::access::address_space::private_space, DecoratedAddress>`:
7890  // - `ET`: cv-unqualified trivial type
7891  constexpr auto CheckType = [](QualType RT, const ASTContext &Ctx) {
7892  if (!SemaSYCL::isSyclType(RT, SYCLTypeAttr::multi_ptr))
7893  return true;
7894  // Check element type
7895  const TemplateArgumentList &TAL =
7896  cast<ClassTemplateSpecializationDecl>(RT->getAsRecordDecl())
7897  ->getTemplateArgs();
7898  QualType ET = TAL.get(0).getAsType();
7899  if (ET.isConstQualified() || ET.isVolatileQualified() ||
7900  !ET.isTrivialType(Ctx))
7901  return true;
7902  constexpr uint64_t PrivateAS = 0;
7903  return TAL.get(1).getAsIntegral() != PrivateAS;
7904  };
7905  if (CheckType(FD->getReturnType(), getASTContext())) {
7906  Diag(Loc, diag::err_intel_sycl_alloca_wrong_type)
7907  << IsAlignedAlloca << FD->getReturnType();
7908  return true;
7909  }
7910 
7911  // Check size is passed as a specialization constant
7912  const auto CheckSize = [this, IsAlignedAlloca, ElementTypeIndex,
7913  SpecNameIndex](const ASTContext &Ctx,
7914  SourceLocation Loc,
7915  const TemplateArgumentList *CST) {
7916  TemplateArgument TA = CST->get(SpecNameIndex);
7918  if (Ty.isNull() || !Ty->isReferenceType())
7919  return true;
7920  Ty = Ty->getPointeeType();
7921  if (!SemaSYCL::isSyclType(Ty, SYCLTypeAttr::specialization_id))
7922  return true;
7923  const TemplateArgumentList &TAL =
7924  cast<ClassTemplateSpecializationDecl>(Ty->getAsCXXRecordDecl())
7925  ->getTemplateArgs();
7926  if (!TAL.get(0).getAsType()->isIntegralType(Ctx))
7927  return true;
7928  llvm::APSInt DefaultSize =
7929  getSYCLAllocaDefaultSize(Ctx, cast<VarDecl>(TA.getAsDecl()));
7930  if (DefaultSize < 1)
7931  Diag(Loc, diag::warn_intel_sycl_alloca_bad_default_value)
7932  << IsAlignedAlloca << DefaultSize.getSExtValue();
7933  return false;
7934  };
7935  if (CheckSize(getASTContext(), Loc, CST)) {
7936  TemplateArgument TA = CST->get(SpecNameIndex);
7938  const SemaDiagnosticBuilder &D =
7939  Diag(Loc, diag::err_intel_sycl_alloca_wrong_size);
7940  D << IsAlignedAlloca;
7941  if (Ty.isNull())
7942  D << TA;
7943  else
7944  D << Ty;
7945  return true;
7946  }
7947 
7948  if (IsAlignedAlloca) {
7949  TemplateArgument AlignmentArg = CST->get(AlignmentIndex);
7950  llvm::APSInt RequestedAlign = AlignmentArg.getAsIntegral();
7951  if (!RequestedAlign.isPowerOf2())
7952  return Diag(Loc, diag::err_alignment_not_power_of_two);
7953  constexpr int32_t MaxAllowedAlign = std::numeric_limits<int32_t>::max() / 8;
7954  if (RequestedAlign > MaxAllowedAlign)
7955  return Diag(Loc, diag::err_alignment_too_big) << MaxAllowedAlign;
7956  QualType AllocaType = CST->get(ElementTypeIndex).getAsType();
7957  int64_t AllocaRequiredAlignment =
7958  Context.getTypeAlignInChars(AllocaType).getQuantity();
7959  if (RequestedAlign < AllocaRequiredAlignment)
7960  return Diag(Loc, diag::err_alignas_underaligned)
7961  << AllocaType << AllocaRequiredAlignment;
7962  }
7963 
7964  return false;
7965 }
7966 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
7967 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
7968 /// Returns true when the format fits the function and the FormatStringInfo has
7969 /// been populated.
7970 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
7971  bool IsVariadic, FormatStringInfo *FSI) {
7972  if (Format->getFirstArg() == 0)
7973  FSI->ArgPassingKind = FAPK_VAList;
7974  else if (IsVariadic)
7975  FSI->ArgPassingKind = FAPK_Variadic;
7976  else
7977  FSI->ArgPassingKind = FAPK_Fixed;
7978  FSI->FormatIdx = Format->getFormatIdx() - 1;
7979  FSI->FirstDataArg =
7980  FSI->ArgPassingKind == FAPK_VAList ? 0 : Format->getFirstArg() - 1;
7981 
7982  // The way the format attribute works in GCC, the implicit this argument
7983  // of member functions is counted. However, it doesn't appear in our own
7984  // lists, so decrement format_idx in that case.
7985  if (IsCXXMember) {
7986  if(FSI->FormatIdx == 0)
7987  return false;
7988  --FSI->FormatIdx;
7989  if (FSI->FirstDataArg != 0)
7990  --FSI->FirstDataArg;
7991  }
7992  return true;
7993 }
7994 
7995 /// Checks if a the given expression evaluates to null.
7996 ///
7997 /// Returns true if the value evaluates to null.
7998 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
7999  // Treat (smart) pointers constructed from nullptr as null, whether we can
8000  // const-evaluate them or not.
8001  // This must happen first: the smart pointer expr might have _Nonnull type!
8002  if (isa<CXXNullPtrLiteralExpr>(
8005  return true;
8006 
8007  // If the expression has non-null type, it doesn't evaluate to null.
8008  if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
8009  if (*nullability == NullabilityKind::NonNull)
8010  return false;
8011  }
8012 
8013  // As a special case, transparent unions initialized with zero are
8014  // considered null for the purposes of the nonnull attribute.
8015  if (const RecordType *UT = Expr->getType()->getAsUnionType();
8016  UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
8017  if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))
8018  if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
8019  Expr = ILE->getInit(0);
8020  }
8021 
8022  bool Result;
8023  return (!Expr->isValueDependent() &&
8024  Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
8025  !Result);
8026 }
8027 
8029  const Expr *ArgExpr,
8030  SourceLocation CallSiteLoc) {
8031  if (CheckNonNullExpr(S, ArgExpr))
8032  S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
8033  S.PDiag(diag::warn_null_arg)
8034  << ArgExpr->getSourceRange());
8035 }
8036 
8037 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
8038  FormatStringInfo FSI;
8039  if ((GetFormatStringType(Format) == FST_NSString) &&
8040  getFormatStringInfo(Format, false, true, &FSI)) {
8041  Idx = FSI.FormatIdx;
8042  return true;
8043  }
8044  return false;
8045 }
8046 
8047 /// Diagnose use of %s directive in an NSString which is being passed
8048 /// as formatting string to formatting method.
8049 static void
8051  const NamedDecl *FDecl,
8052  Expr **Args,
8053  unsigned NumArgs) {
8054  unsigned Idx = 0;
8055  bool Format = false;
8057  if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
8058  Idx = 2;
8059  Format = true;
8060  }
8061  else
8062  for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
8063  if (S.GetFormatNSStringIdx(I, Idx)) {
8064  Format = true;
8065  break;
8066  }
8067  }
8068  if (!Format || NumArgs <= Idx)
8069  return;
8070  const Expr *FormatExpr = Args[Idx];
8071  if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
8072  FormatExpr = CSCE->getSubExpr();
8073  const StringLiteral *FormatString;
8074  if (const ObjCStringLiteral *OSL =
8075  dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
8076  FormatString = OSL->getString();
8077  else
8078  FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
8079  if (!FormatString)
8080  return;
8081  if (S.FormatStringHasSArg(FormatString)) {
8082  S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
8083  << "%s" << 1 << 1;
8084  S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
8085  << FDecl->getDeclName();
8086  }
8087 }
8088 
8089 /// Determine whether the given type has a non-null nullability annotation.
8091  if (auto nullability = type->getNullability())
8092  return *nullability == NullabilityKind::NonNull;
8093 
8094  return false;
8095 }
8096 
8098  const NamedDecl *FDecl,
8099  const FunctionProtoType *Proto,
8101  SourceLocation CallSiteLoc) {
8102  assert((FDecl || Proto) && "Need a function declaration or prototype");
8103 
8104  // Already checked by constant evaluator.
8106  return;
8107  // Check the attributes attached to the method/function itself.
8108  llvm::SmallBitVector NonNullArgs;
8109  if (FDecl) {
8110  // Handle the nonnull attribute on the function/method declaration itself.
8111  for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
8112  if (!NonNull->args_size()) {
8113  // Easy case: all pointer arguments are nonnull.
8114  for (const auto *Arg : Args)
8115  if (S.isValidPointerAttrType(Arg->getType()))
8116  CheckNonNullArgument(S, Arg, CallSiteLoc);
8117  return;
8118  }
8119 
8120  for (const ParamIdx &Idx : NonNull->args()) {
8121  unsigned IdxAST = Idx.getASTIndex();
8122  if (IdxAST >= Args.size())
8123  continue;
8124  if (NonNullArgs.empty())
8125  NonNullArgs.resize(Args.size());
8126  NonNullArgs.set(IdxAST);
8127  }
8128  }
8129  }
8130 
8131  if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
8132  // Handle the nonnull attribute on the parameters of the
8133  // function/method.
8134  ArrayRef<ParmVarDecl*> parms;
8135  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
8136  parms = FD->parameters();
8137  else
8138  parms = cast<ObjCMethodDecl>(FDecl)->parameters();
8139 
8140  unsigned ParamIndex = 0;
8141  for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
8142  I != E; ++I, ++ParamIndex) {
8143  const ParmVarDecl *PVD = *I;
8144  if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
8145  if (NonNullArgs.empty())
8146  NonNullArgs.resize(Args.size());
8147 
8148  NonNullArgs.set(ParamIndex);
8149  }
8150  }
8151  } else {
8152  // If we have a non-function, non-method declaration but no
8153  // function prototype, try to dig out the function prototype.
8154  if (!Proto) {
8155  if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
8156  QualType type = VD->getType().getNonReferenceType();
8157  if (auto pointerType = type->getAs<PointerType>())
8158  type = pointerType->getPointeeType();
8159  else if (auto blockType = type->getAs<BlockPointerType>())
8160  type = blockType->getPointeeType();
8161  // FIXME: data member pointers?
8162 
8163  // Dig out the function prototype, if there is one.
8164  Proto = type->getAs<FunctionProtoType>();
8165  }
8166  }
8167 
8168  // Fill in non-null argument information from the nullability
8169  // information on the parameter types (if we have them).
8170  if (Proto) {
8171  unsigned Index = 0;
8172  for (auto paramType : Proto->getParamTypes()) {
8173  if (isNonNullType(paramType)) {
8174  if (NonNullArgs.empty())
8175  NonNullArgs.resize(Args.size());
8176 
8177  NonNullArgs.set(Index);
8178  }
8179 
8180  ++Index;
8181  }
8182  }
8183  }
8184 
8185  // Check for non-null arguments.
8186  for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
8187  ArgIndex != ArgIndexEnd; ++ArgIndex) {
8188  if (NonNullArgs[ArgIndex])
8189  CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
8190  }
8191 }
8192 
8193 // 16 byte ByVal alignment not due to a vector member is not honoured by XL
8194 // on AIX. Emit a warning here that users are generating binary incompatible
8195 // code to be safe.
8196 // Here we try to get information about the alignment of the struct member
8197 // from the struct passed to the caller function. We only warn when the struct
8198 // is passed byval, hence the series of checks and early returns if we are a not
8199 // passing a struct byval.
8200 void Sema::checkAIXMemberAlignment(SourceLocation Loc, const Expr *Arg) {
8201  const auto *ICE = dyn_cast<ImplicitCastExpr>(Arg->IgnoreParens());
8202  if (!ICE)
8203  return;
8204 
8205  const auto *DR = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
8206  if (!DR)
8207  return;
8208 
8209  const auto *PD = dyn_cast<ParmVarDecl>(DR->getDecl());
8210  if (!PD || !PD->getType()->isRecordType())
8211  return;
8212 
8213  QualType ArgType = Arg->getType();
8214  for (const FieldDecl *FD :
8215  ArgType->castAs<RecordType>()->getDecl()->fields()) {
8216  if (const auto *AA = FD->getAttr<AlignedAttr>()) {
8217  CharUnits Alignment =
8218  Context.toCharUnitsFromBits(AA->getAlignment(Context));
8219  if (Alignment.getQuantity() == 16) {
8220  Diag(FD->getLocation(), diag::warn_not_xl_compatible) << FD;
8221  Diag(Loc, diag::note_misaligned_member_used_here) << PD;
8222  }
8223  }
8224  }
8225 }
8226 
8227 /// Warn if a pointer or reference argument passed to a function points to an
8228 /// object that is less aligned than the parameter. This can happen when
8229 /// creating a typedef with a lower alignment than the original type and then
8230 /// calling functions defined in terms of the original type.
8231 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
8232  StringRef ParamName, QualType ArgTy,
8233  QualType ParamTy) {
8234 
8235  // If a function accepts a pointer or reference type
8236  if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
8237  return;
8238 
8239  // If the parameter is a pointer type, get the pointee type for the
8240  // argument too. If the parameter is a reference type, don't try to get
8241  // the pointee type for the argument.
8242  if (ParamTy->isPointerType())
8243  ArgTy = ArgTy->getPointeeType();
8244 
8245  // Remove reference or pointer
8246  ParamTy = ParamTy->getPointeeType();
8247 
8248  // Find expected alignment, and the actual alignment of the passed object.
8249  // getTypeAlignInChars requires complete types
8250  if (ArgTy.isNull() || ParamTy->isDependentType() ||
8251  ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
8252  ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
8253  return;
8254 
8255  CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
8256  CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
8257 
8258  // If the argument is less aligned than the parameter, there is a
8259  // potential alignment issue.
8260  if (ArgAlign < ParamAlign)
8261  Diag(Loc, diag::warn_param_mismatched_alignment)
8262  << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
8263  << ParamName << (FDecl != nullptr) << FDecl;
8264 }
8265 
8266 /// Handles the checks for format strings, non-POD arguments to vararg
8267 /// functions, NULL arguments passed to non-NULL parameters, diagnose_if
8268 /// attributes and AArch64 SME attributes.
8269 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
8270  const Expr *ThisArg, ArrayRef<const Expr *> Args,
8271  bool IsMemberFunction, SourceLocation Loc,
8272  SourceRange Range, VariadicCallType CallType) {
8273  // FIXME: We should check as much as we can in the template definition.
8274  if (CurContext->isDependentContext())
8275  return;
8276 
8277  // Printf and scanf checking.
8278  llvm::SmallBitVector CheckedVarArgs;
8279  if (FDecl) {
8280  for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
8281  // Only create vector if there are format attributes.
8282  CheckedVarArgs.resize(Args.size());
8283 
8284  CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
8285  CheckedVarArgs);
8286  }
8287  }
8288 
8289  // Refuse POD arguments that weren't caught by the format string
8290  // checks above.
8291  auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
8292  if (CallType != VariadicDoesNotApply &&
8293  (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
8294  unsigned NumParams = Proto ? Proto->getNumParams()
8295  : FDecl && isa<FunctionDecl>(FDecl)
8296  ? cast<FunctionDecl>(FDecl)->getNumParams()
8297  : FDecl && isa<ObjCMethodDecl>(FDecl)
8298  ? cast<ObjCMethodDecl>(FDecl)->param_size()
8299  : 0;
8300 
8301  for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
8302  // Args[ArgIdx] can be null in malformed code.
8303  if (const Expr *Arg = Args[ArgIdx]) {
8304  if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
8305  checkVariadicArgument(Arg, CallType);
8306  }
8307  }
8308  }
8309 
8310  if (FDecl || Proto) {
8311  CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
8312 
8313  // Type safety checking.
8314  if (FDecl) {
8315  for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
8316  CheckArgumentWithTypeTag(I, Args, Loc);
8317  }
8318  }
8319 
8320  // Check that passed arguments match the alignment of original arguments.
8321  // Try to get the missing prototype from the declaration.
8322  if (!Proto && FDecl) {
8323  const auto *FT = FDecl->getFunctionType();
8324  if (isa_and_nonnull<FunctionProtoType>(FT))
8325  Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
8326  }
8327  if (Proto) {
8328  // For variadic functions, we may have more args than parameters.
8329  // For some K&R functions, we may have less args than parameters.
8330  const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
8331  bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
8332  bool IsScalableArg = false;
8333  for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
8334  // Args[ArgIdx] can be null in malformed code.
8335  if (const Expr *Arg = Args[ArgIdx]) {
8336  if (Arg->containsErrors())
8337  continue;
8338 
8339  if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
8340  FDecl->hasLinkage() &&
8341  FDecl->getFormalLinkage() != Linkage::Internal &&
8342  CallType == VariadicDoesNotApply)
8343  checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
8344 
8345  QualType ParamTy = Proto->getParamType(ArgIdx);
8346  if (ParamTy->isSizelessVectorType())
8347  IsScalableArg = true;
8348  QualType ArgTy = Arg->getType();
8349  CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
8350  ArgTy, ParamTy);
8351  }
8352  }
8353 
8354  // If the callee has an AArch64 SME attribute to indicate that it is an
8355  // __arm_streaming function, then the caller requires SME to be available.
8358  if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
8359  llvm::StringMap<bool> CallerFeatureMap;
8360  Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
8361  if (!CallerFeatureMap.contains("sme"))
8362  Diag(Loc, diag::err_sme_call_in_non_sme_target);
8363  } else if (!Context.getTargetInfo().hasFeature("sme")) {
8364  Diag(Loc, diag::err_sme_call_in_non_sme_target);
8365  }
8366  }
8367 
8368  // If the call requires a streaming-mode change and has scalable vector
8369  // arguments or return values, then warn the user that the streaming and
8370  // non-streaming vector lengths may be different.
8371  const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext);
8372  if (CallerFD && (!FD || !FD->getBuiltinID()) &&
8373  (IsScalableArg || IsScalableRet)) {
8374  bool IsCalleeStreaming =
8376  bool IsCalleeStreamingCompatible =
8377  ExtInfo.AArch64SMEAttributes &
8379  ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);
8380  if (!IsCalleeStreamingCompatible &&
8381  (CallerFnType == ArmStreamingCompatible ||
8382  ((CallerFnType == ArmStreaming) ^ IsCalleeStreaming))) {
8383  if (IsScalableArg)
8384  Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
8385  << /*IsArg=*/true;
8386  if (IsScalableRet)
8387  Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
8388  << /*IsArg=*/false;
8389  }
8390  }
8391 
8392  FunctionType::ArmStateValue CalleeArmZAState =
8394  FunctionType::ArmStateValue CalleeArmZT0State =
8396  if (CalleeArmZAState != FunctionType::ARM_None ||
8397  CalleeArmZT0State != FunctionType::ARM_None) {
8398  bool CallerHasZAState = false;
8399  bool CallerHasZT0State = false;
8400  if (CallerFD) {
8401  auto *Attr = CallerFD->getAttr<ArmNewAttr>();
8402  if (Attr && Attr->isNewZA())
8403  CallerHasZAState = true;
8404  if (Attr && Attr->isNewZT0())
8405  CallerHasZT0State = true;
8406  if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
8407  CallerHasZAState |=
8409  FPT->getExtProtoInfo().AArch64SMEAttributes) !=
8411  CallerHasZT0State |=
8413  FPT->getExtProtoInfo().AArch64SMEAttributes) !=
8415  }
8416  }
8417 
8418  if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
8419  Diag(Loc, diag::err_sme_za_call_no_za_state);
8420 
8421  if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
8422  Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
8423 
8424  if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
8425  CalleeArmZT0State != FunctionType::ARM_None) {
8426  Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
8427  Diag(Loc, diag::note_sme_use_preserves_za);
8428  }
8429  }
8430  }
8431 
8432  if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
8433  auto *AA = FDecl->getAttr<AllocAlignAttr>();
8434  const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
8435  if (!Arg->isValueDependent()) {
8436  Expr::EvalResult Align;
8437  if (Arg->EvaluateAsInt(Align, Context)) {
8438  const llvm::APSInt &I = Align.Val.getInt();
8439  if (!I.isPowerOf2())
8440  Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
8441  << Arg->getSourceRange();
8442 
8443  if (I > Sema::MaximumAlignment)
8444  Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
8445  << Arg->getSourceRange() << Sema::MaximumAlignment;
8446  }
8447  }
8448  }
8449 
8450  if (FD)
8451  diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
8452 
8453  if (FD && FD->hasAttr<SYCLKernelAttr>())
8454  SYCL().CheckSYCLKernelCall(FD, Args);
8455 
8456  // Diagnose variadic calls in SYCL.
8457  if (FD && FD->isVariadic() && getLangOpts().SYCLIsDevice &&
8458  !isUnevaluatedContext() && !SYCL().isDeclAllowedInSYCLDeviceCode(FD))
8459  SYCL().DiagIfDeviceCode(Loc, diag::err_sycl_restrict)
8461 }
8462 
8463 /// CheckConstructorCall - Check a constructor call for correctness and safety
8464 /// properties not enforced by the C type system.
8465 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
8467  const FunctionProtoType *Proto,
8468  SourceLocation Loc) {
8469  VariadicCallType CallType =
8470  Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
8471 
8472  auto *Ctor = cast<CXXConstructorDecl>(FDecl);
8473  CheckArgAlignment(
8474  Loc, FDecl, "'this'", Context.getPointerType(ThisType),
8475  Context.getPointerType(Ctor->getFunctionObjectParameterType()));
8476 
8477  checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
8478  Loc, SourceRange(), CallType);
8479 }
8480 
8481 /// CheckFunctionCall - Check a direct function call for various correctness
8482 /// and safety properties not strictly enforced by the C type system.
8484  const FunctionProtoType *Proto) {
8485  bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
8486  isa<CXXMethodDecl>(FDecl);
8487  bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
8488  IsMemberOperatorCall;
8489  VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
8490  TheCall->getCallee());
8491  Expr** Args = TheCall->getArgs();
8492  unsigned NumArgs = TheCall->getNumArgs();
8493 
8494  Expr *ImplicitThis = nullptr;
8495  if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
8496  // If this is a call to a member operator, hide the first
8497  // argument from checkCall.
8498  // FIXME: Our choice of AST representation here is less than ideal.
8499  ImplicitThis = Args[0];
8500  ++Args;
8501  --NumArgs;
8502  } else if (IsMemberFunction && !FDecl->isStatic() &&
8504  ImplicitThis =
8505  cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
8506 
8507  if (ImplicitThis) {
8508  // ImplicitThis may or may not be a pointer, depending on whether . or -> is
8509  // used.
8510  QualType ThisType = ImplicitThis->getType();
8511  if (!ThisType->isPointerType()) {
8512  assert(!ThisType->isReferenceType());
8513  ThisType = Context.getPointerType(ThisType);
8514  }
8515 
8516  QualType ThisTypeFromDecl = Context.getPointerType(
8517  cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
8518 
8519  CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
8520  ThisTypeFromDecl);
8521  }
8522 
8523  checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
8524  IsMemberFunction, TheCall->getRParenLoc(),
8525  TheCall->getCallee()->getSourceRange(), CallType);
8526 
8527  IdentifierInfo *FnInfo = FDecl->getIdentifier();
8528  // None of the checks below are needed for functions that don't have
8529  // simple names (e.g., C++ conversion functions).
8530  if (!FnInfo)
8531  return false;
8532 
8533  // Enforce TCB except for builtin calls, which are always allowed.
8534  if (FDecl->getBuiltinID() == 0)
8535  CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
8536 
8537  CheckAbsoluteValueFunction(TheCall, FDecl);
8538  CheckMaxUnsignedZero(TheCall, FDecl);
8539  CheckInfNaNFunction(TheCall, FDecl);
8540 
8541  if (getLangOpts().ObjC)
8542  DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
8543 
8544  unsigned CMId = FDecl->getMemoryFunctionKind();
8545 
8546  // Handle memory setting and copying functions.
8547  switch (CMId) {
8548  case 0:
8549  return false;
8550  case Builtin::BIstrlcpy: // fallthrough
8551  case Builtin::BIstrlcat:
8552  CheckStrlcpycatArguments(TheCall, FnInfo);
8553  break;
8554  case Builtin::BIstrncat:
8555  CheckStrncatArguments(TheCall, FnInfo);
8556  break;
8557  case Builtin::BIfree:
8558  CheckFreeArguments(TheCall);
8559  break;
8560  default:
8561  CheckMemaccessArguments(TheCall, CMId, FnInfo);
8562  }
8563 
8564  return false;
8565 }
8566 
8567 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
8568  ArrayRef<const Expr *> Args) {
8569  VariadicCallType CallType =
8570  Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
8571 
8572  checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
8573  /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
8574  CallType);
8575 
8576  CheckTCBEnforcement(lbrac, Method);
8577 
8578  return false;
8579 }
8580 
8581 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
8582  const FunctionProtoType *Proto) {
8583  QualType Ty;
8584  if (const auto *V = dyn_cast<VarDecl>(NDecl))
8585  Ty = V->getType().getNonReferenceType();
8586  else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
8587  Ty = F->getType().getNonReferenceType();
8588  else
8589  return false;
8590 
8591  if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
8592  !Ty->isFunctionProtoType())
8593  return false;
8594 
8595  VariadicCallType CallType;
8596  if (!Proto || !Proto->isVariadic()) {
8597  CallType = VariadicDoesNotApply;
8598  } else if (Ty->isBlockPointerType()) {
8599  CallType = VariadicBlock;
8600  } else { // Ty->isFunctionPointerType()
8601  CallType = VariadicFunction;
8602  }
8603 
8604  checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
8605  llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
8606  /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
8607  TheCall->getCallee()->getSourceRange(), CallType);
8608 
8609  return false;
8610 }
8611 
8612 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
8613 /// such as function pointers returned from functions.
8614 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
8615  VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
8616  TheCall->getCallee());
8617  checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
8618  llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
8619  /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
8620  TheCall->getCallee()->getSourceRange(), CallType);
8621 
8622  return false;
8623 }
8624 
8626  if (!llvm::isValidAtomicOrderingCABI(Ordering))
8627  return false;
8628 
8629  auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
8630  switch (Op) {
8631  case AtomicExpr::AO__c11_atomic_init:
8632  case AtomicExpr::AO__opencl_atomic_init:
8633  llvm_unreachable("There is no ordering argument for an init");
8634 
8635  case AtomicExpr::AO__c11_atomic_load:
8636  case AtomicExpr::AO__opencl_atomic_load:
8637  case AtomicExpr::AO__hip_atomic_load:
8638  case AtomicExpr::AO__atomic_load_n:
8639  case AtomicExpr::AO__atomic_load:
8640  case AtomicExpr::AO__scoped_atomic_load_n:
8641  case AtomicExpr::AO__scoped_atomic_load:
8642  return OrderingCABI != llvm::AtomicOrderingCABI::release &&
8643  OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
8644 
8645  case AtomicExpr::AO__c11_atomic_store:
8646  case AtomicExpr::AO__opencl_atomic_store:
8647  case AtomicExpr::AO__hip_atomic_store:
8648  case AtomicExpr::AO__atomic_store:
8649  case AtomicExpr::AO__atomic_store_n:
8650  case AtomicExpr::AO__scoped_atomic_store:
8651  case AtomicExpr::AO__scoped_atomic_store_n:
8652  return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
8653  OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
8654  OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
8655 
8656  default:
8657  return true;
8658  }
8659 }
8660 
8661 ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
8662  AtomicExpr::AtomicOp Op) {
8663  CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
8664  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
8665  MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
8666  return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
8667  DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
8668  Op);
8669 }
8670 
8672  SourceLocation RParenLoc, MultiExprArg Args,
8674  AtomicArgumentOrder ArgOrder) {
8675  // All the non-OpenCL operations take one of the following forms.
8676  // The OpenCL operations take the __c11 forms with one extra argument for
8677  // synchronization scope.
8678  enum {
8679  // C __c11_atomic_init(A *, C)
8680  Init,
8681 
8682  // C __c11_atomic_load(A *, int)
8683  Load,
8684 
8685  // void __atomic_load(A *, CP, int)
8686  LoadCopy,
8687 
8688  // void __atomic_store(A *, CP, int)
8689  Copy,
8690 
8691  // C __c11_atomic_add(A *, M, int)
8692  Arithmetic,
8693 
8694  // C __atomic_exchange_n(A *, CP, int)
8695  Xchg,
8696 
8697  // void __atomic_exchange(A *, C *, CP, int)
8698  GNUXchg,
8699 
8700  // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
8701  C11CmpXchg,
8702 
8703  // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
8704  GNUCmpXchg
8705  } Form = Init;
8706 
8707  const unsigned NumForm = GNUCmpXchg + 1;
8708  const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
8709  const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
8710  // where:
8711  // C is an appropriate type,
8712  // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
8713  // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
8714  // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
8715  // the int parameters are for orderings.
8716 
8717  static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
8718  && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
8719  "need to update code for modified forms");
8720  static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
8721  AtomicExpr::AO__atomic_xor_fetch + 1 ==
8722  AtomicExpr::AO__c11_atomic_compare_exchange_strong,
8723  "need to update code for modified C11 atomics");
8724  bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
8725  Op <= AtomicExpr::AO__opencl_atomic_store;
8726  bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
8727  Op <= AtomicExpr::AO__hip_atomic_store;
8728  bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
8729  Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
8730  bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
8731  Op <= AtomicExpr::AO__c11_atomic_store) ||
8732  IsOpenCL;
8733  bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
8734  Op == AtomicExpr::AO__atomic_store_n ||
8735  Op == AtomicExpr::AO__atomic_exchange_n ||
8736  Op == AtomicExpr::AO__atomic_compare_exchange_n ||
8737  Op == AtomicExpr::AO__scoped_atomic_load_n ||
8738  Op == AtomicExpr::AO__scoped_atomic_store_n ||
8739  Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
8740  Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
8741  // Bit mask for extra allowed value types other than integers for atomic
8742  // arithmetic operations. Add/sub allow pointer and floating point. Min/max
8743  // allow floating point.
8744  enum ArithOpExtraValueType {
8745  AOEVT_None = 0,
8746  AOEVT_Pointer = 1,
8747  AOEVT_FP = 2,
8748  };
8749  unsigned ArithAllows = AOEVT_None;
8750 
8751  switch (Op) {
8752  case AtomicExpr::AO__c11_atomic_init:
8753  case AtomicExpr::AO__opencl_atomic_init:
8754  Form = Init;
8755  break;
8756 
8757  case AtomicExpr::AO__c11_atomic_load:
8758  case AtomicExpr::AO__opencl_atomic_load:
8759  case AtomicExpr::AO__hip_atomic_load:
8760  case AtomicExpr::AO__atomic_load_n:
8761  case AtomicExpr::AO__scoped_atomic_load_n:
8762  Form = Load;
8763  break;
8764 
8765  case AtomicExpr::AO__atomic_load:
8766  case AtomicExpr::AO__scoped_atomic_load:
8767  Form = LoadCopy;
8768  break;
8769 
8770  case AtomicExpr::AO__c11_atomic_store:
8771  case AtomicExpr::AO__opencl_atomic_store:
8772  case AtomicExpr::AO__hip_atomic_store:
8773  case AtomicExpr::AO__atomic_store:
8774  case AtomicExpr::AO__atomic_store_n:
8775  case AtomicExpr::AO__scoped_atomic_store:
8776  case AtomicExpr::AO__scoped_atomic_store_n:
8777  Form = Copy;
8778  break;
8779  case AtomicExpr::AO__atomic_fetch_add:
8780  case AtomicExpr::AO__atomic_fetch_sub:
8781  case AtomicExpr::AO__atomic_add_fetch:
8782  case AtomicExpr::AO__atomic_sub_fetch:
8783  case AtomicExpr::AO__scoped_atomic_fetch_add:
8784  case AtomicExpr::AO__scoped_atomic_fetch_sub:
8785  case AtomicExpr::AO__scoped_atomic_add_fetch:
8786  case AtomicExpr::AO__scoped_atomic_sub_fetch:
8787  case AtomicExpr::AO__c11_atomic_fetch_add:
8788  case AtomicExpr::AO__c11_atomic_fetch_sub:
8789  case AtomicExpr::AO__opencl_atomic_fetch_add:
8790  case AtomicExpr::AO__opencl_atomic_fetch_sub:
8791  case AtomicExpr::AO__hip_atomic_fetch_add:
8792  case AtomicExpr::AO__hip_atomic_fetch_sub:
8793  ArithAllows = AOEVT_Pointer | AOEVT_FP;
8794  Form = Arithmetic;
8795  break;
8796  case AtomicExpr::AO__atomic_fetch_max:
8797  case AtomicExpr::AO__atomic_fetch_min:
8798  case AtomicExpr::AO__atomic_max_fetch:
8799  case AtomicExpr::AO__atomic_min_fetch:
8800  case AtomicExpr::AO__scoped_atomic_fetch_max:
8801  case AtomicExpr::AO__scoped_atomic_fetch_min:
8802  case AtomicExpr::AO__scoped_atomic_max_fetch:
8803  case AtomicExpr::AO__scoped_atomic_min_fetch:
8804  case AtomicExpr::AO__c11_atomic_fetch_max:
8805  case AtomicExpr::AO__c11_atomic_fetch_min:
8806  case AtomicExpr::AO__opencl_atomic_fetch_max:
8807  case AtomicExpr::AO__opencl_atomic_fetch_min:
8808  case AtomicExpr::AO__hip_atomic_fetch_max:
8809  case AtomicExpr::AO__hip_atomic_fetch_min:
8810  ArithAllows = AOEVT_FP;
8811  Form = Arithmetic;
8812  break;
8813  case AtomicExpr::AO__c11_atomic_fetch_and:
8814  case AtomicExpr::AO__c11_atomic_fetch_or:
8815  case AtomicExpr::AO__c11_atomic_fetch_xor:
8816  case AtomicExpr::AO__hip_atomic_fetch_and:
8817  case AtomicExpr::AO__hip_atomic_fetch_or:
8818  case AtomicExpr::AO__hip_atomic_fetch_xor:
8819  case AtomicExpr::AO__c11_atomic_fetch_nand:
8820  case AtomicExpr::AO__opencl_atomic_fetch_and:
8821  case AtomicExpr::AO__opencl_atomic_fetch_or:
8822  case AtomicExpr::AO__opencl_atomic_fetch_xor:
8823  case AtomicExpr::AO__atomic_fetch_and:
8824  case AtomicExpr::AO__atomic_fetch_or:
8825  case AtomicExpr::AO__atomic_fetch_xor:
8826  case AtomicExpr::AO__atomic_fetch_nand:
8827  case AtomicExpr::AO__atomic_and_fetch:
8828  case AtomicExpr::AO__atomic_or_fetch:
8829  case AtomicExpr::AO__atomic_xor_fetch:
8830  case AtomicExpr::AO__atomic_nand_fetch:
8831  case AtomicExpr::AO__scoped_atomic_fetch_and:
8832  case AtomicExpr::AO__scoped_atomic_fetch_or:
8833  case AtomicExpr::AO__scoped_atomic_fetch_xor:
8834  case AtomicExpr::AO__scoped_atomic_fetch_nand:
8835  case AtomicExpr::AO__scoped_atomic_and_fetch:
8836  case AtomicExpr::AO__scoped_atomic_or_fetch:
8837  case AtomicExpr::AO__scoped_atomic_xor_fetch:
8838  case AtomicExpr::AO__scoped_atomic_nand_fetch:
8839  Form = Arithmetic;
8840  break;
8841 
8842  case AtomicExpr::AO__c11_atomic_exchange:
8843  case AtomicExpr::AO__hip_atomic_exchange:
8844  case AtomicExpr::AO__opencl_atomic_exchange:
8845  case AtomicExpr::AO__atomic_exchange_n:
8846  case AtomicExpr::AO__scoped_atomic_exchange_n:
8847  Form = Xchg;
8848  break;
8849 
8850  case AtomicExpr::AO__atomic_exchange:
8851  case AtomicExpr::AO__scoped_atomic_exchange:
8852  Form = GNUXchg;
8853  break;
8854 
8855  case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
8856  case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
8857  case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
8858  case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
8859  case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
8860  case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
8861  Form = C11CmpXchg;
8862  break;
8863 
8864  case AtomicExpr::AO__atomic_compare_exchange:
8865  case AtomicExpr::AO__atomic_compare_exchange_n:
8866  case AtomicExpr::AO__scoped_atomic_compare_exchange:
8867  case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
8868  Form = GNUCmpXchg;
8869  break;
8870  }
8871 
8872  unsigned AdjustedNumArgs = NumArgs[Form];
8873  if ((IsOpenCL || IsHIP || IsScoped) &&
8874  Op != AtomicExpr::AO__opencl_atomic_init)
8875  ++AdjustedNumArgs;
8876  // Check we have the right number of arguments.
8877  if (Args.size() < AdjustedNumArgs) {
8878  Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
8879  << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
8880  << /*is non object*/ 0 << ExprRange;
8881  return ExprError();
8882  } else if (Args.size() > AdjustedNumArgs) {
8883  Diag(Args[AdjustedNumArgs]->getBeginLoc(),
8884  diag::err_typecheck_call_too_many_args)
8885  << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
8886  << /*is non object*/ 0 << ExprRange;
8887  return ExprError();
8888  }
8889 
8890  // Inspect the first argument of the atomic operation.
8891  Expr *Ptr = Args[0];
8892  ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
8893  if (ConvertedPtr.isInvalid())
8894  return ExprError();
8895 
8896  Ptr = ConvertedPtr.get();
8897  const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
8898  if (!pointerType) {
8899  Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
8900  << Ptr->getType() << Ptr->getSourceRange();
8901  return ExprError();
8902  }
8903 
8904  // For a __c11 builtin, this should be a pointer to an _Atomic type.
8905  QualType AtomTy = pointerType->getPointeeType(); // 'A'
8906  QualType ValType = AtomTy; // 'C'
8907  if (IsC11) {
8908  if (!AtomTy->isAtomicType()) {
8909  Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
8910  << Ptr->getType() << Ptr->getSourceRange();
8911  return ExprError();
8912  }
8913  if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
8915  Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
8916  << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
8917  << Ptr->getSourceRange();
8918  return ExprError();
8919  }
8920  ValType = AtomTy->castAs<AtomicType>()->getValueType();
8921  } else if (Form != Load && Form != LoadCopy) {
8922  if (ValType.isConstQualified()) {
8923  Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
8924  << Ptr->getType() << Ptr->getSourceRange();
8925  return ExprError();
8926  }
8927  }
8928 
8929  // For an arithmetic operation, the implied arithmetic must be well-formed.
8930  if (Form == Arithmetic) {
8931  // GCC does not enforce these rules for GNU atomics, but we do to help catch
8932  // trivial type errors.
8933  auto IsAllowedValueType = [&](QualType ValType,
8934  unsigned AllowedType) -> bool {
8935  if (ValType->isIntegerType())
8936  return true;
8937  if (ValType->isPointerType())
8938  return AllowedType & AOEVT_Pointer;
8939  if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
8940  return false;
8941  // LLVM Parser does not allow atomicrmw with x86_fp80 type.
8942  if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
8943  &Context.getTargetInfo().getLongDoubleFormat() ==
8944  &llvm::APFloat::x87DoubleExtended())
8945  return false;
8946  return true;
8947  };
8948  if (!IsAllowedValueType(ValType, ArithAllows)) {
8949  auto DID = ArithAllows & AOEVT_FP
8950  ? (ArithAllows & AOEVT_Pointer
8951  ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
8952  : diag::err_atomic_op_needs_atomic_int_or_fp)
8953  : diag::err_atomic_op_needs_atomic_int;
8954  Diag(ExprRange.getBegin(), DID)
8955  << IsC11 << Ptr->getType() << Ptr->getSourceRange();
8956  return ExprError();
8957  }
8958  if (IsC11 && ValType->isPointerType() &&
8959  RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
8960  diag::err_incomplete_type)) {
8961  return ExprError();
8962  }
8963  } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
8964  // For __atomic_*_n operations, the value type must be a scalar integral or
8965  // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
8966  Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
8967  << IsC11 << Ptr->getType() << Ptr->getSourceRange();
8968  return ExprError();
8969  }
8970 
8971  if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
8972  !AtomTy->isScalarType()) {
8973  // For GNU atomics, require a trivially-copyable type. This is not part of
8974  // the GNU atomics specification but we enforce it for consistency with
8975  // other atomics which generally all require a trivially-copyable type. This
8976  // is because atomics just copy bits.
8977  Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
8978  << Ptr->getType() << Ptr->getSourceRange();
8979  return ExprError();
8980  }
8981 
8982  switch (ValType.getObjCLifetime()) {
8983  case Qualifiers::OCL_None:
8985  // okay
8986  break;
8987 
8988  case Qualifiers::OCL_Weak:
8991  // FIXME: Can this happen? By this point, ValType should be known
8992  // to be trivially copyable.
8993  Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
8994  << ValType << Ptr->getSourceRange();
8995  return ExprError();
8996  }
8997 
8998  // All atomic operations have an overload which takes a pointer to a volatile
8999  // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
9000  // into the result or the other operands. Similarly atomic_load takes a
9001  // pointer to a const 'A'.
9002  ValType.removeLocalVolatile();
9003  ValType.removeLocalConst();
9004  QualType ResultType = ValType;
9005  if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
9006  Form == Init)
9007  ResultType = Context.VoidTy;
9008  else if (Form == C11CmpXchg || Form == GNUCmpXchg)
9009  ResultType = Context.BoolTy;
9010 
9011  // The type of a parameter passed 'by value'. In the GNU atomics, such
9012  // arguments are actually passed as pointers.
9013  QualType ByValType = ValType; // 'CP'
9014  bool IsPassedByAddress = false;
9015  if (!IsC11 && !IsHIP && !IsN) {
9016  ByValType = Ptr->getType();
9017  IsPassedByAddress = true;
9018  }
9019 
9020  SmallVector<Expr *, 5> APIOrderedArgs;
9021  if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
9022  APIOrderedArgs.push_back(Args[0]);
9023  switch (Form) {
9024  case Init:
9025  case Load:
9026  APIOrderedArgs.push_back(Args[1]); // Val1/Order
9027  break;
9028  case LoadCopy:
9029  case Copy:
9030  case Arithmetic:
9031  case Xchg:
9032  APIOrderedArgs.push_back(Args[2]); // Val1
9033  APIOrderedArgs.push_back(Args[1]); // Order
9034  break;
9035  case GNUXchg:
9036  APIOrderedArgs.push_back(Args[2]); // Val1
9037  APIOrderedArgs.push_back(Args[3]); // Val2
9038  APIOrderedArgs.push_back(Args[1]); // Order
9039  break;
9040  case C11CmpXchg:
9041  APIOrderedArgs.push_back(Args[2]); // Val1
9042  APIOrderedArgs.push_back(Args[4]); // Val2
9043  APIOrderedArgs.push_back(Args[1]); // Order
9044  APIOrderedArgs.push_back(Args[3]); // OrderFail
9045  break;
9046  case GNUCmpXchg:
9047  APIOrderedArgs.push_back(Args[2]); // Val1
9048  APIOrderedArgs.push_back(Args[4]); // Val2
9049  APIOrderedArgs.push_back(Args[5]); // Weak
9050  APIOrderedArgs.push_back(Args[1]); // Order
9051  APIOrderedArgs.push_back(Args[3]); // OrderFail
9052  break;
9053  }
9054  } else
9055  APIOrderedArgs.append(Args.begin(), Args.end());
9056 
9057  // The first argument's non-CV pointer type is used to deduce the type of
9058  // subsequent arguments, except for:
9059  // - weak flag (always converted to bool)
9060  // - memory order (always converted to int)
9061  // - scope (always converted to int)
9062  for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
9063  QualType Ty;
9064  if (i < NumVals[Form] + 1) {
9065  switch (i) {
9066  case 0:
9067  // The first argument is always a pointer. It has a fixed type.
9068  // It is always dereferenced, a nullptr is undefined.
9069  CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
9070  // Nothing else to do: we already know all we want about this pointer.
9071  continue;
9072  case 1:
9073  // The second argument is the non-atomic operand. For arithmetic, this
9074  // is always passed by value, and for a compare_exchange it is always
9075  // passed by address. For the rest, GNU uses by-address and C11 uses
9076  // by-value.
9077  assert(Form != Load);
9078  if (Form == Arithmetic && ValType->isPointerType())
9079  Ty = Context.getPointerDiffType();
9080  else if (Form == Init || Form == Arithmetic)
9081  Ty = ValType;
9082  else if (Form == Copy || Form == Xchg) {
9083  if (IsPassedByAddress) {
9084  // The value pointer is always dereferenced, a nullptr is undefined.
9085  CheckNonNullArgument(*this, APIOrderedArgs[i],
9086  ExprRange.getBegin());
9087  }
9088  Ty = ByValType;
9089  } else {
9090  Expr *ValArg = APIOrderedArgs[i];
9091  // The value pointer is always dereferenced, a nullptr is undefined.
9092  CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
9093  LangAS AS = LangAS::Default;
9094  // Keep address space of non-atomic pointer type.
9095  if (const PointerType *PtrTy =
9096  ValArg->getType()->getAs<PointerType>()) {
9097  AS = PtrTy->getPointeeType().getAddressSpace();
9098  }
9099  Ty = Context.getPointerType(
9100  Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
9101  }
9102  break;
9103  case 2:
9104  // The third argument to compare_exchange / GNU exchange is the desired
9105  // value, either by-value (for the C11 and *_n variant) or as a pointer.
9106  if (IsPassedByAddress)
9107  CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
9108  Ty = ByValType;
9109  break;
9110  case 3:
9111  // The fourth argument to GNU compare_exchange is a 'weak' flag.
9112  Ty = Context.BoolTy;
9113  break;
9114  }
9115  } else {
9116  // The order(s) and scope are always converted to int.
9117  Ty = Context.IntTy;
9118  }
9119 
9120  InitializedEntity Entity =
9121  InitializedEntity::InitializeParameter(Context, Ty, false);
9122  ExprResult Arg = APIOrderedArgs[i];
9123  Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
9124  if (Arg.isInvalid())
9125  return true;
9126  APIOrderedArgs[i] = Arg.get();
9127  }
9128 
9129  // Permute the arguments into a 'consistent' order.
9130  SmallVector<Expr*, 5> SubExprs;
9131  SubExprs.push_back(Ptr);
9132  switch (Form) {
9133  case Init:
9134  // Note, AtomicExpr::getVal1() has a special case for this atomic.
9135  SubExprs.push_back(APIOrderedArgs[1]); // Val1
9136  break;
9137  case Load:
9138  SubExprs.push_back(APIOrderedArgs[1]); // Order
9139  break;
9140  case LoadCopy:
9141  case Copy:
9142  case Arithmetic:
9143  case Xchg:
9144  SubExprs.push_back(APIOrderedArgs[2]); // Order
9145  SubExprs.push_back(APIOrderedArgs[1]); // Val1
9146  break;
9147  case GNUXchg:
9148  // Note, AtomicExpr::getVal2() has a special case for this atomic.
9149  SubExprs.push_back(APIOrderedArgs[3]); // Order
9150  SubExprs.push_back(APIOrderedArgs[1]); // Val1
9151  SubExprs.push_back(APIOrderedArgs[2]); // Val2
9152  break;
9153  case C11CmpXchg:
9154  SubExprs.push_back(APIOrderedArgs[3]); // Order
9155  SubExprs.push_back(APIOrderedArgs[1]); // Val1
9156  SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
9157  SubExprs.push_back(APIOrderedArgs[2]); // Val2
9158  break;
9159  case GNUCmpXchg:
9160  SubExprs.push_back(APIOrderedArgs[4]); // Order
9161  SubExprs.push_back(APIOrderedArgs[1]); // Val1
9162  SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
9163  SubExprs.push_back(APIOrderedArgs[2]); // Val2
9164  SubExprs.push_back(APIOrderedArgs[3]); // Weak
9165  break;
9166  }
9167 
9168  // If the memory orders are constants, check they are valid.
9169  if (SubExprs.size() >= 2 && Form != Init) {
9170  std::optional<llvm::APSInt> Success =
9171  SubExprs[1]->getIntegerConstantExpr(Context);
9172  if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
9173  Diag(SubExprs[1]->getBeginLoc(),
9174  diag::warn_atomic_op_has_invalid_memory_order)
9175  << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
9176  << SubExprs[1]->getSourceRange();
9177  }
9178  if (SubExprs.size() >= 5) {
9179  if (std::optional<llvm::APSInt> Failure =
9180  SubExprs[3]->getIntegerConstantExpr(Context)) {
9181  if (!llvm::is_contained(
9182  {llvm::AtomicOrderingCABI::relaxed,
9183  llvm::AtomicOrderingCABI::consume,
9184  llvm::AtomicOrderingCABI::acquire,
9185  llvm::AtomicOrderingCABI::seq_cst},
9186  (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
9187  Diag(SubExprs[3]->getBeginLoc(),
9188  diag::warn_atomic_op_has_invalid_memory_order)
9189  << /*failure=*/2 << SubExprs[3]->getSourceRange();
9190  }
9191  }
9192  }
9193  }
9194 
9195  if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
9196  auto *Scope = Args[Args.size() - 1];
9197  if (std::optional<llvm::APSInt> Result =
9198  Scope->getIntegerConstantExpr(Context)) {
9199  if (!ScopeModel->isValid(Result->getZExtValue()))
9200  Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
9201  << Scope->getSourceRange();
9202  }
9203  SubExprs.push_back(Scope);
9204  }
9205 
9206  AtomicExpr *AE = new (Context)
9207  AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
9208 
9209  if ((Op == AtomicExpr::AO__c11_atomic_load ||
9210  Op == AtomicExpr::AO__c11_atomic_store ||
9211  Op == AtomicExpr::AO__opencl_atomic_load ||
9212  Op == AtomicExpr::AO__hip_atomic_load ||
9213  Op == AtomicExpr::AO__opencl_atomic_store ||
9214  Op == AtomicExpr::AO__hip_atomic_store) &&
9215  Context.AtomicUsesUnsupportedLibcall(AE))
9216  Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
9217  << ((Op == AtomicExpr::AO__c11_atomic_load ||
9218  Op == AtomicExpr::AO__opencl_atomic_load ||
9219  Op == AtomicExpr::AO__hip_atomic_load)
9220  ? 0
9221  : 1);
9222 
9223  if (ValType->isBitIntType()) {
9224  Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
9225  return ExprError();
9226  }
9227 
9228  return AE;
9229 }
9230 
9231 /// checkBuiltinArgument - Given a call to a builtin function, perform
9232 /// normal type-checking on the given argument, updating the call in
9233 /// place. This is useful when a builtin function requires custom
9234 /// type-checking for some of its arguments but not necessarily all of
9235 /// them.
9236 ///
9237 /// Returns true on error.
9238 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
9239  FunctionDecl *Fn = E->getDirectCallee();
9240  assert(Fn && "builtin call without direct callee!");
9241 
9242  ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
9243  InitializedEntity Entity =
9245 
9246  ExprResult Arg = E->getArg(ArgIndex);
9247  Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
9248  if (Arg.isInvalid())
9249  return true;
9250 
9251  E->setArg(ArgIndex, Arg.get());
9252  return false;
9253 }
9254 
9255 bool Sema::BuiltinWasmRefNullExtern(CallExpr *TheCall) {
9256  if (TheCall->getNumArgs() != 0)
9257  return true;
9258 
9259  TheCall->setType(Context.getWebAssemblyExternrefType());
9260 
9261  return false;
9262 }
9263 
9264 bool Sema::BuiltinWasmRefNullFunc(CallExpr *TheCall) {
9265  if (TheCall->getNumArgs() != 0) {
9266  Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_many_args)
9267  << 0 /*function call*/ << /*expected*/ 0 << TheCall->getNumArgs()
9268  << /*is non object*/ 0;
9269  return true;
9270  }
9271 
9272  // This custom type checking code ensures that the nodes are as expected
9273  // in order to later on generate the necessary builtin.
9274  QualType Pointee = Context.getFunctionType(Context.VoidTy, {}, {});
9275  QualType Type = Context.getPointerType(Pointee);
9276  Pointee = Context.getAddrSpaceQualType(Pointee, LangAS::wasm_funcref);
9277  Type = Context.getAttributedType(attr::WebAssemblyFuncref, Type,
9278  Context.getPointerType(Pointee));
9279  TheCall->setType(Type);
9280 
9281  return false;
9282 }
9283 
9284 /// We have a call to a function like __sync_fetch_and_add, which is an
9285 /// overloaded function based on the pointer type of its first argument.
9286 /// The main BuildCallExpr routines have already promoted the types of
9287 /// arguments because all of these calls are prototyped as void(...).
9288 ///
9289 /// This function goes through and does final semantic checking for these
9290 /// builtins, as well as generating any warnings.
9291 ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
9292  CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
9293  Expr *Callee = TheCall->getCallee();
9294  DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
9295  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
9296 
9297  // Ensure that we have at least one argument to do type inference from.
9298  if (TheCall->getNumArgs() < 1) {
9299  Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
9300  << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
9301  << Callee->getSourceRange();
9302  return ExprError();
9303  }
9304 
9305  // Inspect the first argument of the atomic builtin. This should always be
9306  // a pointer type, whose element is an integral scalar or pointer type.
9307  // Because it is a pointer type, we don't have to worry about any implicit
9308  // casts here.
9309  // FIXME: We don't allow floating point scalars as input.
9310  Expr *FirstArg = TheCall->getArg(0);
9311  ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
9312  if (FirstArgResult.isInvalid())
9313  return ExprError();
9314  FirstArg = FirstArgResult.get();
9315  TheCall->setArg(0, FirstArg);
9316 
9317  const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
9318  if (!pointerType) {
9319  Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
9320  << FirstArg->getType() << FirstArg->getSourceRange();
9321  return ExprError();
9322  }
9323 
9324  QualType ValType = pointerType->getPointeeType();
9325  if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
9326  !ValType->isBlockPointerType()) {
9327  Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
9328  << FirstArg->getType() << FirstArg->getSourceRange();
9329  return ExprError();
9330  }
9331 
9332  if (ValType.isConstQualified()) {
9333  Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
9334  << FirstArg->getType() << FirstArg->getSourceRange();
9335  return ExprError();
9336  }
9337 
9338  switch (ValType.getObjCLifetime()) {
9339  case Qualifiers::OCL_None:
9341  // okay
9342  break;
9343 
9344  case Qualifiers::OCL_Weak:
9347  Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
9348  << ValType << FirstArg->getSourceRange();
9349  return ExprError();
9350  }
9351 
9352  // Strip any qualifiers off ValType.
9353  ValType = ValType.getUnqualifiedType();
9354 
9355  // The majority of builtins return a value, but a few have special return
9356  // types, so allow them to override appropriately below.
9357  QualType ResultType = ValType;
9358 
9359  // We need to figure out which concrete builtin this maps onto. For example,
9360  // __sync_fetch_and_add with a 2 byte object turns into
9361  // __sync_fetch_and_add_2.
9362 #define BUILTIN_ROW(x) \
9363  { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
9364  Builtin::BI##x##_8, Builtin::BI##x##_16 }
9365 
9366  static const unsigned BuiltinIndices[][5] = {
9367  BUILTIN_ROW(__sync_fetch_and_add),
9368  BUILTIN_ROW(__sync_fetch_and_sub),
9369  BUILTIN_ROW(__sync_fetch_and_or),
9370  BUILTIN_ROW(__sync_fetch_and_and),
9371  BUILTIN_ROW(__sync_fetch_and_xor),
9372  BUILTIN_ROW(__sync_fetch_and_nand),
9373 
9374  BUILTIN_ROW(__sync_add_and_fetch),
9375  BUILTIN_ROW(__sync_sub_and_fetch),
9376  BUILTIN_ROW(__sync_and_and_fetch),
9377  BUILTIN_ROW(__sync_or_and_fetch),
9378  BUILTIN_ROW(__sync_xor_and_fetch),
9379  BUILTIN_ROW(__sync_nand_and_fetch),
9380 
9381  BUILTIN_ROW(__sync_val_compare_and_swap),
9382  BUILTIN_ROW(__sync_bool_compare_and_swap),
9383  BUILTIN_ROW(__sync_lock_test_and_set),
9384  BUILTIN_ROW(__sync_lock_release),
9385  BUILTIN_ROW(__sync_swap)
9386  };
9387 #undef BUILTIN_ROW
9388 
9389  // Determine the index of the size.
9390  unsigned SizeIndex;
9391  switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
9392  case 1: SizeIndex = 0; break;
9393  case 2: SizeIndex = 1; break;
9394  case 4: SizeIndex = 2; break;
9395  case 8: SizeIndex = 3; break;
9396  case 16: SizeIndex = 4; break;
9397  default:
9398  Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
9399  << FirstArg->getType() << FirstArg->getSourceRange();
9400  return ExprError();
9401  }
9402 
9403  // Each of these builtins has one pointer argument, followed by some number of
9404  // values (0, 1 or 2) followed by a potentially empty varags list of stuff
9405  // that we ignore. Find out which row of BuiltinIndices to read from as well
9406  // as the number of fixed args.
9407  unsigned BuiltinID = FDecl->getBuiltinID();
9408  unsigned BuiltinIndex, NumFixed = 1;
9409  bool WarnAboutSemanticsChange = false;
9410  switch (BuiltinID) {
9411  default: llvm_unreachable("Unknown overloaded atomic builtin!");
9412  case Builtin::BI__sync_fetch_and_add:
9413  case Builtin::BI__sync_fetch_and_add_1:
9414  case Builtin::BI__sync_fetch_and_add_2:
9415  case Builtin::BI__sync_fetch_and_add_4:
9416  case Builtin::BI__sync_fetch_and_add_8:
9417  case Builtin::BI__sync_fetch_and_add_16:
9418  BuiltinIndex = 0;
9419  break;
9420 
9421  case Builtin::BI__sync_fetch_and_sub:
9422  case Builtin::BI__sync_fetch_and_sub_1:
9423  case Builtin::BI__sync_fetch_and_sub_2:
9424  case Builtin::BI__sync_fetch_and_sub_4:
9425  case Builtin::BI__sync_fetch_and_sub_8:
9426  case Builtin::BI__sync_fetch_and_sub_16:
9427  BuiltinIndex = 1;
9428  break;
9429 
9430  case Builtin::BI__sync_fetch_and_or:
9431  case Builtin::BI__sync_fetch_and_or_1:
9432  case Builtin::BI__sync_fetch_and_or_2:
9433  case Builtin::BI__sync_fetch_and_or_4:
9434  case Builtin::BI__sync_fetch_and_or_8:
9435  case Builtin::BI__sync_fetch_and_or_16:
9436  BuiltinIndex = 2;
9437  break;
9438 
9439  case Builtin::BI__sync_fetch_and_and:
9440  case Builtin::BI__sync_fetch_and_and_1:
9441  case Builtin::BI__sync_fetch_and_and_2:
9442  case Builtin::BI__sync_fetch_and_and_4:
9443  case Builtin::BI__sync_fetch_and_and_8:
9444  case Builtin::BI__sync_fetch_and_and_16:
9445  BuiltinIndex = 3;
9446  break;
9447 
9448  case Builtin::BI__sync_fetch_and_xor:
9449  case Builtin::BI__sync_fetch_and_xor_1:
9450  case Builtin::BI__sync_fetch_and_xor_2:
9451  case Builtin::BI__sync_fetch_and_xor_4:
9452  case Builtin::BI__sync_fetch_and_xor_8:
9453  case Builtin::BI__sync_fetch_and_xor_16:
9454  BuiltinIndex = 4;
9455  break;
9456 
9457  case Builtin::BI__sync_fetch_and_nand:
9458  case Builtin::BI__sync_fetch_and_nand_1:
9459  case Builtin::BI__sync_fetch_and_nand_2:
9460  case Builtin::BI__sync_fetch_and_nand_4:
9461  case Builtin::BI__sync_fetch_and_nand_8:
9462  case Builtin::BI__sync_fetch_and_nand_16:
9463  BuiltinIndex = 5;
9464  WarnAboutSemanticsChange = true;
9465  break;
9466 
9467  case Builtin::BI__sync_add_and_fetch:
9468  case Builtin::BI__sync_add_and_fetch_1:
9469  case Builtin::BI__sync_add_and_fetch_2:
9470  case Builtin::BI__sync_add_and_fetch_4:
9471  case Builtin::BI__sync_add_and_fetch_8:
9472  case Builtin::BI__sync_add_and_fetch_16:
9473  BuiltinIndex = 6;
9474  break;
9475 
9476  case Builtin::BI__sync_sub_and_fetch:
9477  case Builtin::BI__sync_sub_and_fetch_1:
9478  case Builtin::BI__sync_sub_and_fetch_2:
9479  case Builtin::BI__sync_sub_and_fetch_4:
9480  case Builtin::BI__sync_sub_and_fetch_8:
9481  case Builtin::BI__sync_sub_and_fetch_16:
9482  BuiltinIndex = 7;
9483  break;
9484 
9485  case Builtin::BI__sync_and_and_fetch:
9486  case Builtin::BI__sync_and_and_fetch_1:
9487  case Builtin::BI__sync_and_and_fetch_2:
9488  case Builtin::BI__sync_and_and_fetch_4:
9489  case Builtin::BI__sync_and_and_fetch_8:
9490  case Builtin::BI__sync_and_and_fetch_16:
9491  BuiltinIndex = 8;
9492  break;
9493 
9494  case Builtin::BI__sync_or_and_fetch:
9495  case Builtin::BI__sync_or_and_fetch_1:
9496  case Builtin::BI__sync_or_and_fetch_2:
9497  case Builtin::BI__sync_or_and_fetch_4:
9498  case Builtin::BI__sync_or_and_fetch_8:
9499  case Builtin::BI__sync_or_and_fetch_16:
9500  BuiltinIndex = 9;
9501  break;
9502 
9503  case Builtin::BI__sync_xor_and_fetch:
9504  case Builtin::BI__sync_xor_and_fetch_1:
9505  case Builtin::BI__sync_xor_and_fetch_2:
9506  case Builtin::BI__sync_xor_and_fetch_4:
9507  case Builtin::BI__sync_xor_and_fetch_8:
9508  case Builtin::BI__sync_xor_and_fetch_16:
9509  BuiltinIndex = 10;
9510  break;
9511 
9512  case Builtin::BI__sync_nand_and_fetch:
9513  case Builtin::BI__sync_nand_and_fetch_1:
9514  case Builtin::BI__sync_nand_and_fetch_2:
9515  case Builtin::BI__sync_nand_and_fetch_4:
9516  case Builtin::BI__sync_nand_and_fetch_8:
9517  case Builtin::BI__sync_nand_and_fetch_16:
9518  BuiltinIndex = 11;
9519  WarnAboutSemanticsChange = true;
9520  break;
9521 
9522  case Builtin::BI__sync_val_compare_and_swap:
9523  case Builtin::BI__sync_val_compare_and_swap_1:
9524  case Builtin::BI__sync_val_compare_and_swap_2:
9525  case Builtin::BI__sync_val_compare_and_swap_4:
9526  case Builtin::BI__sync_val_compare_and_swap_8:
9527  case Builtin::BI__sync_val_compare_and_swap_16:
9528  BuiltinIndex = 12;
9529  NumFixed = 2;
9530  break;
9531 
9532  case Builtin::BI__sync_bool_compare_and_swap:
9533  case Builtin::BI__sync_bool_compare_and_swap_1:
9534  case Builtin::BI__sync_bool_compare_and_swap_2:
9535  case Builtin::BI__sync_bool_compare_and_swap_4:
9536  case Builtin::BI__sync_bool_compare_and_swap_8:
9537  case Builtin::BI__sync_bool_compare_and_swap_16:
9538  BuiltinIndex = 13;
9539  NumFixed = 2;
9540  ResultType = Context.BoolTy;
9541  break;
9542 
9543  case Builtin::BI__sync_lock_test_and_set:
9544  case Builtin::BI__sync_lock_test_and_set_1:
9545  case Builtin::BI__sync_lock_test_and_set_2:
9546  case Builtin::BI__sync_lock_test_and_set_4:
9547  case Builtin::BI__sync_lock_test_and_set_8:
9548  case Builtin::BI__sync_lock_test_and_set_16:
9549  BuiltinIndex = 14;
9550  break;
9551 
9552  case Builtin::BI__sync_lock_release:
9553  case Builtin::BI__sync_lock_release_1:
9554  case Builtin::BI__sync_lock_release_2:
9555  case Builtin::BI__sync_lock_release_4:
9556  case Builtin::BI__sync_lock_release_8:
9557  case Builtin::BI__sync_lock_release_16:
9558  BuiltinIndex = 15;
9559  NumFixed = 0;
9560  ResultType = Context.VoidTy;
9561  break;
9562 
9563  case Builtin::BI__sync_swap:
9564  case Builtin::BI__sync_swap_1:
9565  case Builtin::BI__sync_swap_2:
9566  case Builtin::BI__sync_swap_4:
9567  case Builtin::BI__sync_swap_8:
9568  case Builtin::BI__sync_swap_16:
9569  BuiltinIndex = 16;
9570  break;
9571  }
9572 
9573  // Now that we know how many fixed arguments we expect, first check that we
9574  // have at least that many.
9575  if (TheCall->getNumArgs() < 1+NumFixed) {
9576  Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
9577  << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
9578  << Callee->getSourceRange();
9579  return ExprError();
9580  }
9581 
9582  Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
9583  << Callee->getSourceRange();
9584 
9585  if (WarnAboutSemanticsChange) {
9586  Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
9587  << Callee->getSourceRange();
9588  }
9589 
9590  // Get the decl for the concrete builtin from this, we can tell what the
9591  // concrete integer type we should convert to is.
9592  unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
9593  StringRef NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
9594  FunctionDecl *NewBuiltinDecl;
9595  if (NewBuiltinID == BuiltinID)
9596  NewBuiltinDecl = FDecl;
9597  else {
9598  // Perform builtin lookup to avoid redeclaring it.
9599  DeclarationName DN(&Context.Idents.get(NewBuiltinName));
9600  LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
9601  LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
9602  assert(Res.getFoundDecl());
9603  NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
9604  if (!NewBuiltinDecl)
9605  return ExprError();
9606  }
9607 
9608  // The first argument --- the pointer --- has a fixed type; we
9609  // deduce the types of the rest of the arguments accordingly. Walk
9610  // the remaining arguments, converting them to the deduced value type.
9611  for (unsigned i = 0; i != NumFixed; ++i) {
9612  ExprResult Arg = TheCall->getArg(i+1);
9613 
9614  // GCC does an implicit conversion to the pointer or integer ValType. This
9615  // can fail in some cases (1i -> int**), check for this error case now.
9616  // Initialize the argument.
9618  ValType, /*consume*/ false);
9619  Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
9620  if (Arg.isInvalid())
9621  return ExprError();
9622 
9623  // Okay, we have something that *can* be converted to the right type. Check
9624  // to see if there is a potentially weird extension going on here. This can
9625  // happen when you do an atomic operation on something like an char* and
9626  // pass in 42. The 42 gets converted to char. This is even more strange
9627  // for things like 45.123 -> char, etc.
9628  // FIXME: Do this check.
9629  TheCall->setArg(i+1, Arg.get());
9630  }
9631 
9632  // Create a new DeclRefExpr to refer to the new decl.
9633  DeclRefExpr *NewDRE = DeclRefExpr::Create(
9634  Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
9635  /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
9636  DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
9637 
9638  // Set the callee in the CallExpr.
9639  // FIXME: This loses syntactic information.
9640  QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
9641  ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
9642  CK_BuiltinFnToFnPtr);
9643  TheCall->setCallee(PromotedCall.get());
9644 
9645  // Change the result type of the call to match the original value type. This
9646  // is arbitrary, but the codegen for these builtins ins design to handle it
9647  // gracefully.
9648  TheCall->setType(ResultType);
9649 
9650  // Prohibit problematic uses of bit-precise integer types with atomic
9651  // builtins. The arguments would have already been converted to the first
9652  // argument's type, so only need to check the first argument.
9653  const auto *BitIntValType = ValType->getAs<BitIntType>();
9654  if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
9655  Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
9656  return ExprError();
9657  }
9658 
9659  return TheCallResult;
9660 }
9661 
9662 /// BuiltinNontemporalOverloaded - We have a call to
9663 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
9664 /// overloaded function based on the pointer type of its last argument.
9665 ///
9666 /// This function goes through and does final semantic checking for these
9667 /// builtins.
9668 ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
9669  CallExpr *TheCall = (CallExpr *)TheCallResult.get();
9670  DeclRefExpr *DRE =
9671  cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
9672  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
9673  unsigned BuiltinID = FDecl->getBuiltinID();
9674  assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
9675  BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
9676  "Unexpected nontemporal load/store builtin!");
9677  bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
9678  unsigned numArgs = isStore ? 2 : 1;
9679 
9680  // Ensure that we have the proper number of arguments.
9681  if (checkArgCount(*this, TheCall, numArgs))
9682  return ExprError();
9683 
9684  // Inspect the last argument of the nontemporal builtin. This should always
9685  // be a pointer type, from which we imply the type of the memory access.
9686  // Because it is a pointer type, we don't have to worry about any implicit
9687  // casts here.
9688  Expr *PointerArg = TheCall->getArg(numArgs - 1);
9689  ExprResult PointerArgResult =
9690  DefaultFunctionArrayLvalueConversion(PointerArg);
9691 
9692  if (PointerArgResult.isInvalid())
9693  return ExprError();
9694  PointerArg = PointerArgResult.get();
9695  TheCall->setArg(numArgs - 1, PointerArg);
9696 
9697  const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
9698  if (!pointerType) {
9699  Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
9700  << PointerArg->getType() << PointerArg->getSourceRange();
9701  return ExprError();
9702  }
9703 
9704  QualType ValType = pointerType->getPointeeType();
9705 
9706  // Strip any qualifiers off ValType.
9707  ValType = ValType.getUnqualifiedType();
9708  if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
9709  !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
9710  !ValType->isVectorType()) {
9711  Diag(DRE->getBeginLoc(),
9712  diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
9713  << PointerArg->getType() << PointerArg->getSourceRange();
9714  return ExprError();
9715  }
9716 
9717  if (!isStore) {
9718  TheCall->setType(ValType);
9719  return TheCallResult;
9720  }
9721 
9722  ExprResult ValArg = TheCall->getArg(0);
9724  Context, ValType, /*consume*/ false);
9725  ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
9726  if (ValArg.isInvalid())
9727  return ExprError();
9728 
9729  TheCall->setArg(0, ValArg.get());
9730  TheCall->setType(Context.VoidTy);
9731  return TheCallResult;
9732 }
9733 
9734 /// CheckObjCString - Checks that the argument to the builtin
9735 /// CFString constructor is correct
9736 /// Note: It might also make sense to do the UTF-16 conversion here (would
9737 /// simplify the backend).
9738 bool Sema::CheckObjCString(Expr *Arg) {
9739  Arg = Arg->IgnoreParenCasts();
9740  StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
9741 
9742  if (!Literal || !Literal->isOrdinary()) {
9743  Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
9744  << Arg->getSourceRange();
9745  return true;
9746  }
9747 
9748  if (Literal->containsNonAsciiOrNull()) {
9749  StringRef String = Literal->getString();
9750  unsigned NumBytes = String.size();
9751  SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
9752  const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
9753  llvm::UTF16 *ToPtr = &ToBuf[0];
9754 
9755  llvm::ConversionResult Result =
9756  llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
9757  ToPtr + NumBytes, llvm::strictConversion);
9758  // Check for conversion failure.
9759  if (Result != llvm::conversionOK)
9760  Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
9761  << Arg->getSourceRange();
9762  }
9763  return false;
9764 }
9765 
9766 /// CheckObjCString - Checks that the format string argument to the os_log()
9767 /// and os_trace() functions is correct, and converts it to const char *.
9768 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
9769  Arg = Arg->IgnoreParenCasts();
9770  auto *Literal = dyn_cast<StringLiteral>(Arg);
9771  if (!Literal) {
9772  if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
9773  Literal = ObjcLiteral->getString();
9774  }
9775  }
9776 
9777  if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
9778  return ExprError(
9779  Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
9780  << Arg->getSourceRange());
9781  }
9782 
9783  ExprResult Result(Literal);
9784  QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
9785  InitializedEntity Entity =
9786  InitializedEntity::InitializeParameter(Context, ResultTy, false);
9787  Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
9788  return Result;
9789 }
9790 
9791 /// Check that the user is calling the appropriate va_start builtin for the
9792 /// target and calling convention.
9793 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
9794  const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
9795  bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
9796  bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
9797  TT.getArch() == llvm::Triple::aarch64_32);
9798  bool IsWindows = TT.isOSWindows();
9799  bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
9800  if (IsX64 || IsAArch64) {
9801  CallingConv CC = CC_C;
9802  if (const FunctionDecl *FD = S.getCurFunctionDecl())
9803  CC = FD->getType()->castAs<FunctionType>()->getCallConv();
9804  if (IsMSVAStart) {
9805  // Don't allow this in System V ABI functions.
9806  if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
9807  return S.Diag(Fn->getBeginLoc(),
9808  diag::err_ms_va_start_used_in_sysv_function);
9809  } else {
9810  // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
9811  // On x64 Windows, don't allow this in System V ABI functions.
9812  // (Yes, that means there's no corresponding way to support variadic
9813  // System V ABI functions on Windows.)
9814  if ((IsWindows && CC == CC_X86_64SysV) ||
9815  (!IsWindows && CC == CC_Win64))
9816  return S.Diag(Fn->getBeginLoc(),
9817  diag::err_va_start_used_in_wrong_abi_function)
9818  << !IsWindows;
9819  }
9820  return false;
9821  }
9822 
9823  if (IsMSVAStart)
9824  return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
9825  return false;
9826 }
9827 
9829  ParmVarDecl **LastParam = nullptr) {
9830  // Determine whether the current function, block, or obj-c method is variadic
9831  // and get its parameter list.
9832  bool IsVariadic = false;
9833  ArrayRef<ParmVarDecl *> Params;
9834  DeclContext *Caller = S.CurContext;
9835  if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
9836  IsVariadic = Block->isVariadic();
9837  Params = Block->parameters();
9838  } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
9839  IsVariadic = FD->isVariadic();
9840  Params = FD->parameters();
9841  } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
9842  IsVariadic = MD->isVariadic();
9843  // FIXME: This isn't correct for methods (results in bogus warning).
9844  Params = MD->parameters();
9845  } else if (isa<CapturedDecl>(Caller)) {
9846  // We don't support va_start in a CapturedDecl.
9847  S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
9848  return true;
9849  } else {
9850  // This must be some other declcontext that parses exprs.
9851  S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
9852  return true;
9853  }
9854 
9855  if (!IsVariadic) {
9856  S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
9857  return true;
9858  }
9859 
9860  if (LastParam)
9861  *LastParam = Params.empty() ? nullptr : Params.back();
9862 
9863  return false;
9864 }
9865 
9866 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
9867 /// for validity. Emit an error and return true on failure; return false
9868 /// on success.
9869 bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
9870  Expr *Fn = TheCall->getCallee();
9871 
9872  if (checkVAStartABI(*this, BuiltinID, Fn))
9873  return true;
9874 
9875  // In C23 mode, va_start only needs one argument. However, the builtin still
9876  // requires two arguments (which matches the behavior of the GCC builtin),
9877  // <stdarg.h> passes `0` as the second argument in C23 mode.
9878  if (checkArgCount(*this, TheCall, 2))
9879  return true;
9880 
9881  // Type-check the first argument normally.
9882  if (checkBuiltinArgument(*this, TheCall, 0))
9883  return true;
9884 
9885  // Check that the current function is variadic, and get its last parameter.
9886  ParmVarDecl *LastParam;
9887  if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
9888  return true;
9889 
9890  // Verify that the second argument to the builtin is the last argument of the
9891  // current function or method. In C23 mode, if the second argument is an
9892  // integer constant expression with value 0, then we don't bother with this
9893  // check.
9894  bool SecondArgIsLastNamedArgument = false;
9895  const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
9896  if (std::optional<llvm::APSInt> Val =
9897  TheCall->getArg(1)->getIntegerConstantExpr(Context);
9898  Val && LangOpts.C23 && *Val == 0)
9899  return false;
9900 
9901  // These are valid if SecondArgIsLastNamedArgument is false after the next
9902  // block.
9903  QualType Type;
9904  SourceLocation ParamLoc;
9905  bool IsCRegister = false;
9906 
9907  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
9908  if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
9909  SecondArgIsLastNamedArgument = PV == LastParam;
9910 
9911  Type = PV->getType();
9912  ParamLoc = PV->getLocation();
9913  IsCRegister =
9914  PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
9915  }
9916  }
9917 
9918  if (!SecondArgIsLastNamedArgument)
9919  Diag(TheCall->getArg(1)->getBeginLoc(),
9920  diag::warn_second_arg_of_va_start_not_last_named_param);
9921  else if (IsCRegister || Type->isReferenceType() ||
9923  // Promotable integers are UB, but enumerations need a bit of
9924  // extra checking to see what their promotable type actually is.
9925  if (!Context.isPromotableIntegerType(Type))
9926  return false;
9927  if (!Type->isEnumeralType())
9928  return true;
9929  const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
9930  return !(ED &&
9931  Context.typesAreCompatible(ED->getPromotionType(), Type));
9932  }()) {
9933  unsigned Reason = 0;
9934  if (Type->isReferenceType()) Reason = 1;
9935  else if (IsCRegister) Reason = 2;
9936  Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
9937  Diag(ParamLoc, diag::note_parameter_type) << Type;
9938  }
9939 
9940  return false;
9941 }
9942 
9943 bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
9944  auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
9945  const LangOptions &LO = getLangOpts();
9946 
9947  if (LO.CPlusPlus)
9948  return Arg->getType()
9949  .getCanonicalType()
9950  .getTypePtr()
9951  ->getPointeeType()
9952  .withoutLocalFastQualifiers() == Context.CharTy;
9953 
9954  // In C, allow aliasing through `char *`, this is required for AArch64 at
9955  // least.
9956  return true;
9957  };
9958 
9959  // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
9960  // const char *named_addr);
9961 
9962  Expr *Func = Call->getCallee();
9963 
9964  if (Call->getNumArgs() < 3)
9965  return Diag(Call->getEndLoc(),
9966  diag::err_typecheck_call_too_few_args_at_least)
9967  << 0 /*function call*/ << 3 << Call->getNumArgs()
9968  << /*is non object*/ 0;
9969 
9970  // Type-check the first argument normally.
9971  if (checkBuiltinArgument(*this, Call, 0))
9972  return true;
9973 
9974  // Check that the current function is variadic.
9975  if (checkVAStartIsInVariadicFunction(*this, Func))
9976  return true;
9977 
9978  // __va_start on Windows does not validate the parameter qualifiers
9979 
9980  const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
9981  const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
9982 
9983  const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
9984  const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
9985 
9986  const QualType &ConstCharPtrTy =
9987  Context.getPointerType(Context.CharTy.withConst());
9988  if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
9989  Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
9990  << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
9991  << 0 /* qualifier difference */
9992  << 3 /* parameter mismatch */
9993  << 2 << Arg1->getType() << ConstCharPtrTy;
9994 
9995  const QualType SizeTy = Context.getSizeType();
9996  if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
9997  Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
9998  << Arg2->getType() << SizeTy << 1 /* different class */
9999  << 0 /* qualifier difference */
10000  << 3 /* parameter mismatch */
10001  << 3 << Arg2->getType() << SizeTy;
10002 
10003  return false;
10004 }
10005 
10006 /// BuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
10007 /// friends. This is declared to take (...), so we have to check everything.
10008 bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
10009  if (checkArgCount(*this, TheCall, 2))
10010  return true;
10011 
10012  if (BuiltinID == Builtin::BI__builtin_isunordered &&
10013  TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
10014  Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10015  << 1 << 0 << TheCall->getSourceRange();
10016 
10017  ExprResult OrigArg0 = TheCall->getArg(0);
10018  ExprResult OrigArg1 = TheCall->getArg(1);
10019 
10020  // Do standard promotions between the two arguments, returning their common
10021  // type.
10022  QualType Res = UsualArithmeticConversions(
10023  OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
10024  if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
10025  return true;
10026 
10027  // Make sure any conversions are pushed back into the call; this is
10028  // type safe since unordered compare builtins are declared as "_Bool
10029  // foo(...)".
10030  TheCall->setArg(0, OrigArg0.get());
10031  TheCall->setArg(1, OrigArg1.get());
10032 
10033  if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
10034  return false;
10035 
10036  // If the common type isn't a real floating type, then the arguments were
10037  // invalid for this operation.
10038  if (Res.isNull() || !Res->isRealFloatingType())
10039  return Diag(OrigArg0.get()->getBeginLoc(),
10040  diag::err_typecheck_call_invalid_ordered_compare)
10041  << OrigArg0.get()->getType() << OrigArg1.get()->getType()
10042  << SourceRange(OrigArg0.get()->getBeginLoc(),
10043  OrigArg1.get()->getEndLoc());
10044 
10045  return false;
10046 }
10047 
10048 /// BuiltinSemaBuiltinFPClassification - Handle functions like
10049 /// __builtin_isnan and friends. This is declared to take (...), so we have
10050 /// to check everything.
10051 bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
10052  unsigned BuiltinID) {
10053  if (checkArgCount(*this, TheCall, NumArgs))
10054  return true;
10055 
10056  FPOptions FPO = TheCall->getFPFeaturesInEffect(getLangOpts());
10057  if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
10058  BuiltinID == Builtin::BI__builtin_isinf ||
10059  BuiltinID == Builtin::BI__builtin_isinf_sign))
10060  Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10061  << 0 << 0 << TheCall->getSourceRange();
10062 
10063  if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
10064  BuiltinID == Builtin::BI__builtin_isunordered))
10065  Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10066  << 1 << 0 << TheCall->getSourceRange();
10067 
10068  bool IsFPClass = NumArgs == 2;
10069 
10070  // Find out position of floating-point argument.
10071  unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
10072 
10073  // We can count on all parameters preceding the floating-point just being int.
10074  // Try all of those.
10075  for (unsigned i = 0; i < FPArgNo; ++i) {
10076  Expr *Arg = TheCall->getArg(i);
10077 
10078  if (Arg->isTypeDependent())
10079  return false;
10080 
10081  ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
10082 
10083  if (Res.isInvalid())
10084  return true;
10085  TheCall->setArg(i, Res.get());
10086  }
10087 
10088  Expr *OrigArg = TheCall->getArg(FPArgNo);
10089 
10090  if (OrigArg->isTypeDependent())
10091  return false;
10092 
10093  // Usual Unary Conversions will convert half to float, which we want for
10094  // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
10095  // type how it is, but do normal L->Rvalue conversions.
10097  OrigArg = UsualUnaryConversions(OrigArg).get();
10098  else
10099  OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
10100  TheCall->setArg(FPArgNo, OrigArg);
10101 
10102  QualType VectorResultTy;
10103  QualType ElementTy = OrigArg->getType();
10104  // TODO: When all classification function are implemented with is_fpclass,
10105  // vector argument can be supported in all of them.
10106  if (ElementTy->isVectorType() && IsFPClass) {
10107  VectorResultTy = GetSignedVectorType(ElementTy);
10108  ElementTy = ElementTy->castAs<VectorType>()->getElementType();
10109  }
10110 
10111  // This operation requires a non-_Complex floating-point number.
10112  if (!ElementTy->isRealFloatingType())
10113  return Diag(OrigArg->getBeginLoc(),
10114  diag::err_typecheck_call_invalid_unary_fp)
10115  << OrigArg->getType() << OrigArg->getSourceRange();
10116 
10117  // __builtin_isfpclass has integer parameter that specify test mask. It is
10118  // passed in (...), so it should be analyzed completely here.
10119  if (IsFPClass)
10120  if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))
10121  return true;
10122 
10123  // TODO: enable this code to all classification functions.
10124  if (IsFPClass) {
10125  QualType ResultTy;
10126  if (!VectorResultTy.isNull())
10127  ResultTy = VectorResultTy;
10128  else
10129  ResultTy = Context.IntTy;
10130  TheCall->setType(ResultTy);
10131  }
10132 
10133  return false;
10134 }
10135 
10136 /// Perform semantic analysis for a call to __builtin_complex.
10137 bool Sema::BuiltinComplex(CallExpr *TheCall) {
10138  if (checkArgCount(*this, TheCall, 2))
10139  return true;
10140 
10141  bool Dependent = false;
10142  for (unsigned I = 0; I != 2; ++I) {
10143  Expr *Arg = TheCall->getArg(I);
10144  QualType T = Arg->getType();
10145  if (T->isDependentType()) {
10146  Dependent = true;
10147  continue;
10148  }
10149 
10150  // Despite supporting _Complex int, GCC requires a real floating point type
10151  // for the operands of __builtin_complex.
10152  if (!T->isRealFloatingType()) {
10153  return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
10154  << Arg->getType() << Arg->getSourceRange();
10155  }
10156 
10157  ExprResult Converted = DefaultLvalueConversion(Arg);
10158  if (Converted.isInvalid())
10159  return true;
10160  TheCall->setArg(I, Converted.get());
10161  }
10162 
10163  if (Dependent) {
10164  TheCall->setType(Context.DependentTy);
10165  return false;
10166  }
10167 
10168  Expr *Real = TheCall->getArg(0);
10169  Expr *Imag = TheCall->getArg(1);
10170  if (!Context.hasSameType(Real->getType(), Imag->getType())) {
10171  return Diag(Real->getBeginLoc(),
10172  diag::err_typecheck_call_different_arg_types)
10173  << Real->getType() << Imag->getType()
10174  << Real->getSourceRange() << Imag->getSourceRange();
10175  }
10176 
10177  // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
10178  // don't allow this builtin to form those types either.
10179  // FIXME: Should we allow these types?
10180  if (Real->getType()->isFloat16Type())
10181  return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
10182  << "_Float16";
10183  if (Real->getType()->isHalfType())
10184  return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
10185  << "half";
10186 
10187  TheCall->setType(Context.getComplexType(Real->getType()));
10188  return false;
10189 }
10190 
10191 // Customized Sema Checking for VSX builtins that have the following signature:
10192 // vector [...] builtinName(vector [...], vector [...], const int);
10193 // Which takes the same type of vectors (any legal vector type) for the first
10194 // two arguments and takes compile time constant for the third argument.
10195 // Example builtins are :
10196 // vector double vec_xxpermdi(vector double, vector double, int);
10197 // vector short vec_xxsldwi(vector short, vector short, int);
10198 bool Sema::BuiltinVSX(CallExpr *TheCall) {
10199  unsigned ExpectedNumArgs = 3;
10200  if (checkArgCount(*this, TheCall, ExpectedNumArgs))
10201  return true;
10202 
10203  // Check the third argument is a compile time constant
10204  if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
10205  return Diag(TheCall->getBeginLoc(),
10206  diag::err_vsx_builtin_nonconstant_argument)
10207  << 3 /* argument index */ << TheCall->getDirectCallee()
10208  << SourceRange(TheCall->getArg(2)->getBeginLoc(),
10209  TheCall->getArg(2)->getEndLoc());
10210 
10211  QualType Arg1Ty = TheCall->getArg(0)->getType();
10212  QualType Arg2Ty = TheCall->getArg(1)->getType();
10213 
10214  // Check the type of argument 1 and argument 2 are vectors.
10215  SourceLocation BuiltinLoc = TheCall->getBeginLoc();
10216  if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
10217  (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
10218  return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
10219  << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ false
10220  << SourceRange(TheCall->getArg(0)->getBeginLoc(),
10221  TheCall->getArg(1)->getEndLoc());
10222  }
10223 
10224  // Check the first two arguments are the same type.
10225  if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
10226  return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
10227  << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ false
10228  << SourceRange(TheCall->getArg(0)->getBeginLoc(),
10229  TheCall->getArg(1)->getEndLoc());
10230  }
10231 
10232  // When default clang type checking is turned off and the customized type
10233  // checking is used, the returning type of the function must be explicitly
10234  // set. Otherwise it is _Bool by default.
10235  TheCall->setType(Arg1Ty);
10236 
10237  return false;
10238 }
10239 
10240 /// BuiltinShuffleVector - Handle __builtin_shufflevector.
10241 // This is declared to take (...), so we have to check everything.
10243  if (TheCall->getNumArgs() < 2)
10244  return ExprError(Diag(TheCall->getEndLoc(),
10245  diag::err_typecheck_call_too_few_args_at_least)
10246  << 0 /*function call*/ << 2 << TheCall->getNumArgs()
10247  << /*is non object*/ 0 << TheCall->getSourceRange());
10248 
10249  // Determine which of the following types of shufflevector we're checking:
10250  // 1) unary, vector mask: (lhs, mask)
10251  // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
10252  QualType resType = TheCall->getArg(0)->getType();
10253  unsigned numElements = 0;
10254 
10255  if (!TheCall->getArg(0)->isTypeDependent() &&
10256  !TheCall->getArg(1)->isTypeDependent()) {
10257  QualType LHSType = TheCall->getArg(0)->getType();
10258  QualType RHSType = TheCall->getArg(1)->getType();
10259 
10260  if (!LHSType->isVectorType() || !RHSType->isVectorType())
10261  return ExprError(
10262  Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
10263  << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ false
10264  << SourceRange(TheCall->getArg(0)->getBeginLoc(),
10265  TheCall->getArg(1)->getEndLoc()));
10266 
10267  numElements = LHSType->castAs<VectorType>()->getNumElements();
10268  unsigned numResElements = TheCall->getNumArgs() - 2;
10269 
10270  // Check to see if we have a call with 2 vector arguments, the unary shuffle
10271  // with mask. If so, verify that RHS is an integer vector type with the
10272  // same number of elts as lhs.
10273  if (TheCall->getNumArgs() == 2) {
10274  if (!RHSType->hasIntegerRepresentation() ||
10275  RHSType->castAs<VectorType>()->getNumElements() != numElements)
10276  return ExprError(Diag(TheCall->getBeginLoc(),
10277  diag::err_vec_builtin_incompatible_vector)
10278  << TheCall->getDirectCallee()
10279  << /*isMorethantwoArgs*/ false
10280  << SourceRange(TheCall->getArg(1)->getBeginLoc(),
10281  TheCall->getArg(1)->getEndLoc()));
10282  } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
10283  return ExprError(Diag(TheCall->getBeginLoc(),
10284  diag::err_vec_builtin_incompatible_vector)
10285  << TheCall->getDirectCallee()
10286  << /*isMorethantwoArgs*/ false
10287  << SourceRange(TheCall->getArg(0)->getBeginLoc(),
10288  TheCall->getArg(1)->getEndLoc()));
10289  } else if (numElements != numResElements) {
10290  QualType eltType = LHSType->castAs<VectorType>()->getElementType();
10291  resType =
10292  Context.getVectorType(eltType, numResElements, VectorKind::Generic);
10293  }
10294  }
10295 
10296  for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
10297  if (TheCall->getArg(i)->isTypeDependent() ||
10298  TheCall->getArg(i)->isValueDependent())
10299  continue;
10300 
10301  std::optional<llvm::APSInt> Result;
10302  if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
10303  return ExprError(Diag(TheCall->getBeginLoc(),
10304  diag::err_shufflevector_nonconstant_argument)
10305  << TheCall->getArg(i)->getSourceRange());
10306 
10307  // Allow -1 which will be translated to undef in the IR.
10308  if (Result->isSigned() && Result->isAllOnes())
10309  continue;
10310 
10311  if (Result->getActiveBits() > 64 ||
10312  Result->getZExtValue() >= numElements * 2)
10313  return ExprError(Diag(TheCall->getBeginLoc(),
10314  diag::err_shufflevector_argument_too_large)
10315  << TheCall->getArg(i)->getSourceRange());
10316  }
10317 
10318  SmallVector<Expr*, 32> exprs;
10319 
10320  for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
10321  exprs.push_back(TheCall->getArg(i));
10322  TheCall->setArg(i, nullptr);
10323  }
10324 
10325  return new (Context) ShuffleVectorExpr(Context, exprs, resType,
10326  TheCall->getCallee()->getBeginLoc(),
10327  TheCall->getRParenLoc());
10328 }
10329 
10330 /// ConvertVectorExpr - Handle __builtin_convertvector
10332  SourceLocation BuiltinLoc,
10333  SourceLocation RParenLoc) {
10336  QualType DstTy = TInfo->getType();
10337  QualType SrcTy = E->getType();
10338 
10339  if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
10340  return ExprError(Diag(BuiltinLoc,
10341  diag::err_convertvector_non_vector)
10342  << E->getSourceRange());
10343  if (!DstTy->isVectorType() && !DstTy->isDependentType())
10344  return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
10345  << "second"
10346  << "__builtin_convertvector");
10347 
10348  if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
10349  unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
10350  unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
10351  if (SrcElts != DstElts)
10352  return ExprError(Diag(BuiltinLoc,
10353  diag::err_convertvector_incompatible_vector)
10354  << E->getSourceRange());
10355  }
10356 
10357  return new (Context) class ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
10358  BuiltinLoc, RParenLoc);
10359 }
10360 
10361 /// BuiltinPrefetch - Handle __builtin_prefetch.
10362 // This is declared to take (const void*, ...) and can take two
10363 // optional constant int args.
10364 bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
10365  unsigned NumArgs = TheCall->getNumArgs();
10366 
10367  if (checkArgCountAtMost(*this, TheCall, 3))
10368  return true;
10369 
10370  // Argument 0 is checked for us and the remaining arguments must be
10371  // constant integers.
10372  for (unsigned i = 1; i != NumArgs; ++i)
10373  if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
10374  return true;
10375 
10376  return false;
10377 }
10378 
10379 /// BuiltinArithmeticFence - Handle __arithmetic_fence.
10380 bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
10382  return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
10383  << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
10384  if (checkArgCount(*this, TheCall, 1))
10385  return true;
10386  Expr *Arg = TheCall->getArg(0);
10387  if (Arg->isInstantiationDependent())
10388  return false;
10389 
10390  QualType ArgTy = Arg->getType();
10391  if (!ArgTy->hasFloatingRepresentation())
10392  return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
10393  << ArgTy;
10394  if (Arg->isLValue()) {
10395  ExprResult FirstArg = DefaultLvalueConversion(Arg);
10396  TheCall->setArg(0, FirstArg.get());
10397  }
10398  TheCall->setType(TheCall->getArg(0)->getType());
10399  return false;
10400 }
10401 
10402 /// BuiltinAssume - Handle __assume (MS Extension).
10403 // __assume does not evaluate its arguments, and should warn if its argument
10404 // has side effects.
10405 bool Sema::BuiltinAssume(CallExpr *TheCall) {
10406  Expr *Arg = TheCall->getArg(0);
10407  if (Arg->isInstantiationDependent()) return false;
10408 
10409  if (Arg->HasSideEffects(Context))
10410  Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
10411  << Arg->getSourceRange()
10412  << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
10413 
10414  return false;
10415 }
10416 
10417 /// Handle __builtin_alloca_with_align. This is declared
10418 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
10419 /// than 8.
10420 bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
10421  // The alignment must be a constant integer.
10422  Expr *Arg = TheCall->getArg(1);
10423 
10424  // We can't check the value of a dependent argument.
10425  if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
10426  if (const auto *UE =
10427  dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
10428  if (UE->getKind() == UETT_AlignOf ||
10429  UE->getKind() == UETT_PreferredAlignOf)
10430  Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
10431  << Arg->getSourceRange();
10432 
10433  llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
10434 
10435  if (!Result.isPowerOf2())
10436  return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
10437  << Arg->getSourceRange();
10438 
10439  if (Result < Context.getCharWidth())
10440  return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
10441  << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
10442 
10443  if (Result > std::numeric_limits<int32_t>::max())
10444  return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
10446  }
10447 
10448  return false;
10449 }
10450 
10451 /// Handle __builtin_assume_aligned. This is declared
10452 /// as (const void*, size_t, ...) and can take one optional constant int arg.
10453 bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
10454  if (checkArgCountRange(*this, TheCall, 2, 3))
10455  return true;
10456 
10457  unsigned NumArgs = TheCall->getNumArgs();
10458  Expr *FirstArg = TheCall->getArg(0);
10459 
10460  {
10461  ExprResult FirstArgResult =
10462  DefaultFunctionArrayLvalueConversion(FirstArg);
10463  if (checkBuiltinArgument(*this, TheCall, 0))
10464  return true;
10465  /// In-place updation of FirstArg by checkBuiltinArgument is ignored.
10466  TheCall->setArg(0, FirstArgResult.get());
10467  }
10468 
10469  // The alignment must be a constant integer.
10470  Expr *SecondArg = TheCall->getArg(1);
10471 
10472  // We can't check the value of a dependent argument.
10473  if (!SecondArg->isValueDependent()) {
10474  llvm::APSInt Result;
10475  if (BuiltinConstantArg(TheCall, 1, Result))
10476  return true;
10477 
10478  if (!Result.isPowerOf2())
10479  return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
10480  << SecondArg->getSourceRange();
10481 
10482  if (Result > Sema::MaximumAlignment)
10483  Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
10484  << SecondArg->getSourceRange() << Sema::MaximumAlignment;
10485  }
10486 
10487  if (NumArgs > 2) {
10488  Expr *ThirdArg = TheCall->getArg(2);
10489  if (convertArgumentToType(*this, ThirdArg, Context.getSizeType()))
10490  return true;
10491  TheCall->setArg(2, ThirdArg);
10492  }
10493 
10494  return false;
10495 }
10496 
10497 bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
10498  unsigned BuiltinID =
10499  cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
10500  bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
10501 
10502  unsigned NumArgs = TheCall->getNumArgs();
10503  unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
10504  if (NumArgs < NumRequiredArgs) {
10505  return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
10506  << 0 /* function call */ << NumRequiredArgs << NumArgs
10507  << /*is non object*/ 0 << TheCall->getSourceRange();
10508  }
10509  if (checkArgCountAtMost(*this, TheCall, NumRequiredArgs + 0xff))
10510  return true;
10511  unsigned i = 0;
10512 
10513  // For formatting call, check buffer arg.
10514  if (!IsSizeCall) {
10515  ExprResult Arg(TheCall->getArg(i));
10517  Context, Context.VoidPtrTy, false);
10518  Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
10519  if (Arg.isInvalid())
10520  return true;
10521  TheCall->setArg(i, Arg.get());
10522  i++;
10523  }
10524 
10525  // Check string literal arg.
10526  unsigned FormatIdx = i;
10527  {
10528  ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
10529  if (Arg.isInvalid())
10530  return true;
10531  TheCall->setArg(i, Arg.get());
10532  i++;
10533  }
10534 
10535  // Make sure variadic args are scalar.
10536  unsigned FirstDataArg = i;
10537  while (i < NumArgs) {
10538  ExprResult Arg = DefaultVariadicArgumentPromotion(
10539  TheCall->getArg(i), VariadicFunction, nullptr);
10540  if (Arg.isInvalid())
10541  return true;
10542  CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
10543  if (ArgSize.getQuantity() >= 0x100) {
10544  return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
10545  << i << (int)ArgSize.getQuantity() << 0xff
10546  << TheCall->getSourceRange();
10547  }
10548  TheCall->setArg(i, Arg.get());
10549  i++;
10550  }
10551 
10552  // Check formatting specifiers. NOTE: We're only doing this for the non-size
10553  // call to avoid duplicate diagnostics.
10554  if (!IsSizeCall) {
10555  llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
10556  ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
10557  bool Success = CheckFormatArguments(
10558  Args, FAPK_Variadic, FormatIdx, FirstDataArg, FST_OSLog,
10559  VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
10560  CheckedVarArgs);
10561  if (!Success)
10562  return true;
10563  }
10564 
10565  if (IsSizeCall) {
10566  TheCall->setType(Context.getSizeType());
10567  } else {
10568  TheCall->setType(Context.VoidPtrTy);
10569  }
10570  return false;
10571 }
10572 
10573 /// BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
10574 /// TheCall is a constant expression.
10575 bool Sema::BuiltinConstantArg(CallExpr *TheCall, int ArgNum,
10576  llvm::APSInt &Result) {
10577  Expr *Arg = TheCall->getArg(ArgNum);
10578  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
10579  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
10580 
10581  if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
10582 
10583  std::optional<llvm::APSInt> R;
10584  if (!(R = Arg->getIntegerConstantExpr(Context)))
10585  return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
10586  << FDecl->getDeclName() << Arg->getSourceRange();
10587  Result = *R;
10588  return false;
10589 }
10590 
10591 /// BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
10592 /// TheCall is a constant expression in the range [Low, High].
10593 bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
10594  int High, bool RangeIsError) {
10595  if (isConstantEvaluatedContext())
10596  return false;
10597  llvm::APSInt Result;
10598 
10599  // We can't check the value of a dependent argument.
10600  Expr *Arg = TheCall->getArg(ArgNum);
10601  if (Arg->isTypeDependent() || Arg->isValueDependent())
10602  return false;
10603 
10604  // Check constant-ness first.
10605  if (BuiltinConstantArg(TheCall, ArgNum, Result))
10606  return true;
10607 
10608  if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
10609  if (RangeIsError)
10610  return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
10611  << toString(Result, 10) << Low << High << Arg->getSourceRange();
10612  else
10613  // Defer the warning until we know if the code will be emitted so that
10614  // dead code can ignore this.
10615  DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
10616  PDiag(diag::warn_argument_invalid_range)
10617  << toString(Result, 10) << Low << High
10618  << Arg->getSourceRange());
10619  }
10620 
10621  return false;
10622 }
10623 
10624 /// BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
10625 /// TheCall is a constant expression is a multiple of Num..
10626 bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
10627  unsigned Num) {
10628  llvm::APSInt Result;
10629 
10630  // We can't check the value of a dependent argument.
10631  Expr *Arg = TheCall->getArg(ArgNum);
10632  if (Arg->isTypeDependent() || Arg->isValueDependent())
10633  return false;
10634 
10635  // Check constant-ness first.
10636  if (BuiltinConstantArg(TheCall, ArgNum, Result))
10637  return true;
10638 
10639  if (Result.getSExtValue() % Num != 0)
10640  return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
10641  << Num << Arg->getSourceRange();
10642 
10643  return false;
10644 }
10645 
10646 /// BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
10647 /// constant expression representing a power of 2.
10648 bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
10649  llvm::APSInt Result;
10650 
10651  // We can't check the value of a dependent argument.
10652  Expr *Arg = TheCall->getArg(ArgNum);
10653  if (Arg->isTypeDependent() || Arg->isValueDependent())
10654  return false;
10655 
10656  // Check constant-ness first.
10657  if (BuiltinConstantArg(TheCall, ArgNum, Result))
10658  return true;
10659 
10660  // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
10661  // and only if x is a power of 2.
10662  if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
10663  return false;
10664 
10665  return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
10666  << Arg->getSourceRange();
10667 }
10668 
10670  if (Value.isNegative())
10671  return false;
10672 
10673  // Check if it's a shifted byte, by shifting it down
10674  while (true) {
10675  // If the value fits in the bottom byte, the check passes.
10676  if (Value < 0x100)
10677  return true;
10678 
10679  // Otherwise, if the value has _any_ bits in the bottom byte, the check
10680  // fails.
10681  if ((Value & 0xFF) != 0)
10682  return false;
10683 
10684  // If the bottom 8 bits are all 0, but something above that is nonzero,
10685  // then shifting the value right by 8 bits won't affect whether it's a
10686  // shifted byte or not. So do that, and go round again.
10687  Value >>= 8;
10688  }
10689 }
10690 
10691 /// BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
10692 /// a constant expression representing an arbitrary byte value shifted left by
10693 /// a multiple of 8 bits.
10694 bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
10695  unsigned ArgBits) {
10696  llvm::APSInt Result;
10697 
10698  // We can't check the value of a dependent argument.
10699  Expr *Arg = TheCall->getArg(ArgNum);
10700  if (Arg->isTypeDependent() || Arg->isValueDependent())
10701  return false;
10702 
10703  // Check constant-ness first.
10704  if (BuiltinConstantArg(TheCall, ArgNum, Result))
10705  return true;
10706 
10707  // Truncate to the given size.
10708  Result = Result.getLoBits(ArgBits);
10709  Result.setIsUnsigned(true);
10710 
10711  if (IsShiftedByte(Result))
10712  return false;
10713 
10714  return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
10715  << Arg->getSourceRange();
10716 }
10717 
10718 /// BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
10719 /// TheCall is a constant expression representing either a shifted byte value,
10720 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
10721 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
10722 /// Arm MVE intrinsics.
10723 bool Sema::BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum,
10724  unsigned ArgBits) {
10725  llvm::APSInt Result;
10726 
10727  // We can't check the value of a dependent argument.
10728  Expr *Arg = TheCall->getArg(ArgNum);
10729  if (Arg->isTypeDependent() || Arg->isValueDependent())
10730  return false;
10731 
10732  // Check constant-ness first.
10733  if (BuiltinConstantArg(TheCall, ArgNum, Result))
10734  return true;
10735 
10736  // Truncate to the given size.
10737  Result = Result.getLoBits(ArgBits);
10738  Result.setIsUnsigned(true);
10739 
10740  // Check to see if it's in either of the required forms.
10741  if (IsShiftedByte(Result) ||
10742  (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
10743  return false;
10744 
10745  return Diag(TheCall->getBeginLoc(),
10746  diag::err_argument_not_shifted_byte_or_xxff)
10747  << Arg->getSourceRange();
10748 }
10749 
10750 /// BuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
10751 bool Sema::BuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
10752  if (BuiltinID == AArch64::BI__builtin_arm_irg) {
10753  if (checkArgCount(*this, TheCall, 2))
10754  return true;
10755  Expr *Arg0 = TheCall->getArg(0);
10756  Expr *Arg1 = TheCall->getArg(1);
10757 
10758  ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
10759  if (FirstArg.isInvalid())
10760  return true;
10761  QualType FirstArgType = FirstArg.get()->getType();
10762  if (!FirstArgType->isAnyPointerType())
10763  return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
10764  << "first" << FirstArgType << Arg0->getSourceRange();
10765  TheCall->setArg(0, FirstArg.get());
10766 
10767  ExprResult SecArg = DefaultLvalueConversion(Arg1);
10768  if (SecArg.isInvalid())
10769  return true;
10770  QualType SecArgType = SecArg.get()->getType();
10771  if (!SecArgType->isIntegerType())
10772  return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
10773  << "second" << SecArgType << Arg1->getSourceRange();
10774 
10775  // Derive the return type from the pointer argument.
10776  TheCall->setType(FirstArgType);
10777  return false;
10778  }
10779 
10780  if (BuiltinID == AArch64::BI__builtin_arm_addg) {
10781  if (checkArgCount(*this, TheCall, 2))
10782  return true;
10783 
10784  Expr *Arg0 = TheCall->getArg(0);
10785  ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
10786  if (FirstArg.isInvalid())
10787  return true;
10788  QualType FirstArgType = FirstArg.get()->getType();
10789  if (!FirstArgType->isAnyPointerType())
10790  return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
10791  << "first" << FirstArgType << Arg0->getSourceRange();
10792  TheCall->setArg(0, FirstArg.get());
10793 
10794  // Derive the return type from the pointer argument.
10795  TheCall->setType(FirstArgType);
10796 
10797  // Second arg must be an constant in range [0,15]
10798  return BuiltinConstantArgRange(TheCall, 1, 0, 15);
10799  }
10800 
10801  if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
10802  if (checkArgCount(*this, TheCall, 2))
10803  return true;
10804  Expr *Arg0 = TheCall->getArg(0);
10805  Expr *Arg1 = TheCall->getArg(1);
10806 
10807  ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
10808  if (FirstArg.isInvalid())
10809  return true;
10810  QualType FirstArgType = FirstArg.get()->getType();
10811  if (!FirstArgType->isAnyPointerType())
10812  return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
10813  << "first" << FirstArgType << Arg0->getSourceRange();
10814 
10815  QualType SecArgType = Arg1->getType();
10816  if (!SecArgType->isIntegerType())
10817  return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
10818  << "second" << SecArgType << Arg1->getSourceRange();
10819  TheCall->setType(Context.IntTy);
10820  return false;
10821  }
10822 
10823  if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
10824  BuiltinID == AArch64::BI__builtin_arm_stg) {
10825  if (checkArgCount(*this, TheCall, 1))
10826  return true;
10827  Expr *Arg0 = TheCall->getArg(0);
10828  ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
10829  if (FirstArg.isInvalid())
10830  return true;
10831 
10832  QualType FirstArgType = FirstArg.get()->getType();
10833  if (!FirstArgType->isAnyPointerType())
10834  return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
10835  << "first" << FirstArgType << Arg0->getSourceRange();
10836  TheCall->setArg(0, FirstArg.get());
10837 
10838  // Derive the return type from the pointer argument.
10839  if (BuiltinID == AArch64::BI__builtin_arm_ldg)
10840  TheCall->setType(FirstArgType);
10841  return false;
10842  }
10843 
10844  if (BuiltinID == AArch64::BI__builtin_arm_subp) {
10845  Expr *ArgA = TheCall->getArg(0);
10846  Expr *ArgB = TheCall->getArg(1);
10847 
10848  ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
10849  ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
10850 
10851  if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
10852  return true;
10853 
10854  QualType ArgTypeA = ArgExprA.get()->getType();
10855  QualType ArgTypeB = ArgExprB.get()->getType();
10856 
10857  auto isNull = [&] (Expr *E) -> bool {
10858  return E->isNullPointerConstant(
10859  Context, Expr::NPC_ValueDependentIsNotNull); };
10860 
10861  // argument should be either a pointer or null
10862  if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
10863  return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
10864  << "first" << ArgTypeA << ArgA->getSourceRange();
10865 
10866  if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
10867  return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
10868  << "second" << ArgTypeB << ArgB->getSourceRange();
10869 
10870  // Ensure Pointee types are compatible
10871  if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
10872  ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
10873  QualType pointeeA = ArgTypeA->getPointeeType();
10874  QualType pointeeB = ArgTypeB->getPointeeType();
10875  if (!Context.typesAreCompatible(
10876  Context.getCanonicalType(pointeeA).getUnqualifiedType(),
10877  Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
10878  return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
10879  << ArgTypeA << ArgTypeB << ArgA->getSourceRange()
10880  << ArgB->getSourceRange();
10881  }
10882  }
10883 
10884  // at least one argument should be pointer type
10885  if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
10886  return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
10887  << ArgTypeA << ArgTypeB << ArgA->getSourceRange();
10888 
10889  if (isNull(ArgA)) // adopt type of the other pointer
10890  ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
10891 
10892  if (isNull(ArgB))
10893  ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
10894 
10895  TheCall->setArg(0, ArgExprA.get());
10896  TheCall->setArg(1, ArgExprB.get());
10897  TheCall->setType(Context.LongLongTy);
10898  return false;
10899  }
10900  assert(false && "Unhandled ARM MTE intrinsic");
10901  return true;
10902 }
10903 
10904 /// BuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
10905 /// TheCall is an ARM/AArch64 special register string literal.
10906 bool Sema::BuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
10907  int ArgNum, unsigned ExpectedFieldNum,
10908  bool AllowName) {
10909  bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
10910  BuiltinID == ARM::BI__builtin_arm_wsr64 ||
10911  BuiltinID == ARM::BI__builtin_arm_rsr ||
10912  BuiltinID == ARM::BI__builtin_arm_rsrp ||
10913  BuiltinID == ARM::BI__builtin_arm_wsr ||
10914  BuiltinID == ARM::BI__builtin_arm_wsrp;
10915  bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
10916  BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
10917  BuiltinID == AArch64::BI__builtin_arm_rsr128 ||
10918  BuiltinID == AArch64::BI__builtin_arm_wsr128 ||
10919  BuiltinID == AArch64::BI__builtin_arm_rsr ||
10920  BuiltinID == AArch64::BI__builtin_arm_rsrp ||
10921  BuiltinID == AArch64::BI__builtin_arm_wsr ||
10922  BuiltinID == AArch64::BI__builtin_arm_wsrp;
10923  assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
10924 
10925  // We can't check the value of a dependent argument.
10926  Expr *Arg = TheCall->getArg(ArgNum);
10927  if (Arg->isTypeDependent() || Arg->isValueDependent())
10928  return false;
10929 
10930  // Check if the argument is a string literal.
10931  if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
10932  return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
10933  << Arg->getSourceRange();
10934 
10935  // Check the type of special register given.
10936  StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
10938  Reg.split(Fields, ":");
10939 
10940  if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
10941  return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
10942  << Arg->getSourceRange();
10943 
10944  // If the string is the name of a register then we cannot check that it is
10945  // valid here but if the string is of one the forms described in ACLE then we
10946  // can check that the supplied fields are integers and within the valid
10947  // ranges.
10948  if (Fields.size() > 1) {
10949  bool FiveFields = Fields.size() == 5;
10950 
10951  bool ValidString = true;
10952  if (IsARMBuiltin) {
10953  ValidString &= Fields[0].starts_with_insensitive("cp") ||
10954  Fields[0].starts_with_insensitive("p");
10955  if (ValidString)
10956  Fields[0] = Fields[0].drop_front(
10957  Fields[0].starts_with_insensitive("cp") ? 2 : 1);
10958 
10959  ValidString &= Fields[2].starts_with_insensitive("c");
10960  if (ValidString)
10961  Fields[2] = Fields[2].drop_front(1);
10962 
10963  if (FiveFields) {
10964  ValidString &= Fields[3].starts_with_insensitive("c");
10965  if (ValidString)
10966  Fields[3] = Fields[3].drop_front(1);
10967  }
10968  }
10969 
10970  SmallVector<int, 5> Ranges;
10971  if (FiveFields)
10972  Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
10973  else
10974  Ranges.append({15, 7, 15});
10975 
10976  for (unsigned i=0; i<Fields.size(); ++i) {
10977  int IntField;
10978  ValidString &= !Fields[i].getAsInteger(10, IntField);
10979  ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
10980  }
10981 
10982  if (!ValidString)
10983  return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
10984  << Arg->getSourceRange();
10985  } else if (IsAArch64Builtin && Fields.size() == 1) {
10986  // This code validates writes to PSTATE registers.
10987 
10988  // Not a write.
10989  if (TheCall->getNumArgs() != 2)
10990  return false;
10991 
10992  // The 128-bit system register accesses do not touch PSTATE.
10993  if (BuiltinID == AArch64::BI__builtin_arm_rsr128 ||
10994  BuiltinID == AArch64::BI__builtin_arm_wsr128)
10995  return false;
10996 
10997  // These are the named PSTATE accesses using "MSR (immediate)" instructions,
10998  // along with the upper limit on the immediates allowed.
10999  auto MaxLimit = llvm::StringSwitch<std::optional<unsigned>>(Reg)
11000  .CaseLower("spsel", 15)
11001  .CaseLower("daifclr", 15)
11002  .CaseLower("daifset", 15)
11003  .CaseLower("pan", 15)
11004  .CaseLower("uao", 15)
11005  .CaseLower("dit", 15)
11006  .CaseLower("ssbs", 15)
11007  .CaseLower("tco", 15)
11008  .CaseLower("allint", 1)
11009  .CaseLower("pm", 1)
11010  .Default(std::nullopt);
11011 
11012  // If this is not a named PSTATE, just continue without validating, as this
11013  // will be lowered to an "MSR (register)" instruction directly
11014  if (!MaxLimit)
11015  return false;
11016 
11017  // Here we only allow constants in the range for that pstate, as required by
11018  // the ACLE.
11019  //
11020  // While clang also accepts the names of system registers in its ACLE
11021  // intrinsics, we prevent this with the PSTATE names used in MSR (immediate)
11022  // as the value written via a register is different to the value used as an
11023  // immediate to have the same effect. e.g., for the instruction `msr tco,
11024  // x0`, it is bit 25 of register x0 that is written into PSTATE.TCO, but
11025  // with `msr tco, #imm`, it is bit 0 of xN that is written into PSTATE.TCO.
11026  //
11027  // If a programmer wants to codegen the MSR (register) form of `msr tco,
11028  // xN`, they can still do so by specifying the register using five
11029  // colon-separated numbers in a string.
11030  return BuiltinConstantArgRange(TheCall, 1, 0, *MaxLimit);
11031  }
11032 
11033  return false;
11034 }
11035 
11036 /// BuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
11037 /// Emit an error and return true on failure; return false on success.
11038 /// TypeStr is a string containing the type descriptor of the value returned by
11039 /// the builtin and the descriptors of the expected type of the arguments.
11040 bool Sema::BuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
11041  const char *TypeStr) {
11042 
11043  assert((TypeStr[0] != '\0') &&
11044  "Invalid types in PPC MMA builtin declaration");
11045 
11046  unsigned Mask = 0;
11047  unsigned ArgNum = 0;
11048 
11049  // The first type in TypeStr is the type of the value returned by the
11050  // builtin. So we first read that type and change the type of TheCall.
11051  QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
11052  TheCall->setType(type);
11053 
11054  while (*TypeStr != '\0') {
11055  Mask = 0;
11056  QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
11057  if (ArgNum >= TheCall->getNumArgs()) {
11058  ArgNum++;
11059  break;
11060  }
11061 
11062  Expr *Arg = TheCall->getArg(ArgNum);
11063  QualType PassedType = Arg->getType();
11064  QualType StrippedRVType = PassedType.getCanonicalType();
11065 
11066  // Strip Restrict/Volatile qualifiers.
11067  if (StrippedRVType.isRestrictQualified() ||
11068  StrippedRVType.isVolatileQualified())
11069  StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType();
11070 
11071  // The only case where the argument type and expected type are allowed to
11072  // mismatch is if the argument type is a non-void pointer (or array) and
11073  // expected type is a void pointer.
11074  if (StrippedRVType != ExpectedType)
11075  if (!(ExpectedType->isVoidPointerType() &&
11076  (StrippedRVType->isPointerType() || StrippedRVType->isArrayType())))
11077  return Diag(Arg->getBeginLoc(),
11078  diag::err_typecheck_convert_incompatible)
11079  << PassedType << ExpectedType << 1 << 0 << 0;
11080 
11081  // If the value of the Mask is not 0, we have a constraint in the size of
11082  // the integer argument so here we ensure the argument is a constant that
11083  // is in the valid range.
11084  if (Mask != 0 && BuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
11085  return true;
11086 
11087  ArgNum++;
11088  }
11089 
11090  // In case we exited early from the previous loop, there are other types to
11091  // read from TypeStr. So we need to read them all to ensure we have the right
11092  // number of arguments in TheCall and if it is not the case, to display a
11093  // better error message.
11094  while (*TypeStr != '\0') {
11095  (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
11096  ArgNum++;
11097  }
11098  if (checkArgCount(*this, TheCall, ArgNum))
11099  return true;
11100 
11101  return false;
11102 }
11103 
11104 /// BuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
11105 /// This checks that the target supports __builtin_longjmp and
11106 /// that val is a constant 1.
11107 bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
11108  if (!Context.getTargetInfo().hasSjLjLowering())
11109  return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
11110  << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
11111 
11112  Expr *Arg = TheCall->getArg(1);
11113  llvm::APSInt Result;
11114 
11115  // TODO: This is less than ideal. Overload this to take a value.
11116  if (BuiltinConstantArg(TheCall, 1, Result))
11117  return true;
11118 
11119  if (Result != 1)
11120  return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
11121  << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
11122 
11123  return false;
11124 }
11125 
11126 /// BuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
11127 /// This checks that the target supports __builtin_setjmp.
11128 bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
11129  if (!Context.getTargetInfo().hasSjLjLowering())
11130  return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
11131  << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
11132  return false;
11133 }
11134 
11135 namespace {
11136 
11137 class UncoveredArgHandler {
11138  enum { Unknown = -1, AllCovered = -2 };
11139 
11140  signed FirstUncoveredArg = Unknown;
11141  SmallVector<const Expr *, 4> DiagnosticExprs;
11142 
11143 public:
11144  UncoveredArgHandler() = default;
11145 
11146  bool hasUncoveredArg() const {
11147  return (FirstUncoveredArg >= 0);
11148  }
11149 
11150  unsigned getUncoveredArg() const {
11151  assert(hasUncoveredArg() && "no uncovered argument");
11152  return FirstUncoveredArg;
11153  }
11154 
11155  void setAllCovered() {
11156  // A string has been found with all arguments covered, so clear out
11157  // the diagnostics.
11158  DiagnosticExprs.clear();
11159  FirstUncoveredArg = AllCovered;
11160  }
11161 
11162  void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
11163  assert(NewFirstUncoveredArg >= 0 && "Outside range");
11164 
11165  // Don't update if a previous string covers all arguments.
11166  if (FirstUncoveredArg == AllCovered)
11167  return;
11168 
11169  // UncoveredArgHandler tracks the highest uncovered argument index
11170  // and with it all the strings that match this index.
11171  if (NewFirstUncoveredArg == FirstUncoveredArg)
11172  DiagnosticExprs.push_back(StrExpr);
11173  else if (NewFirstUncoveredArg > FirstUncoveredArg) {
11174  DiagnosticExprs.clear();
11175  DiagnosticExprs.push_back(StrExpr);
11176  FirstUncoveredArg = NewFirstUncoveredArg;
11177  }
11178  }
11179 
11180  void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
11181 };
11182 
11183 enum StringLiteralCheckType {
11184  SLCT_NotALiteral,
11185  SLCT_UncheckedLiteral,
11186  SLCT_CheckedLiteral
11187 };
11188 
11189 } // namespace
11190 
11192  BinaryOperatorKind BinOpKind,
11193  bool AddendIsRight) {
11194  unsigned BitWidth = Offset.getBitWidth();
11195  unsigned AddendBitWidth = Addend.getBitWidth();
11196  // There might be negative interim results.
11197  if (Addend.isUnsigned()) {
11198  Addend = Addend.zext(++AddendBitWidth);
11199  Addend.setIsSigned(true);
11200  }
11201  // Adjust the bit width of the APSInts.
11202  if (AddendBitWidth > BitWidth) {
11203  Offset = Offset.sext(AddendBitWidth);
11204  BitWidth = AddendBitWidth;
11205  } else if (BitWidth > AddendBitWidth) {
11206  Addend = Addend.sext(BitWidth);
11207  }
11208 
11209  bool Ov = false;
11210  llvm::APSInt ResOffset = Offset;
11211  if (BinOpKind == BO_Add)
11212  ResOffset = Offset.sadd_ov(Addend, Ov);
11213  else {
11214  assert(AddendIsRight && BinOpKind == BO_Sub &&
11215  "operator must be add or sub with addend on the right");
11216  ResOffset = Offset.ssub_ov(Addend, Ov);
11217  }
11218 
11219  // We add an offset to a pointer here so we should support an offset as big as
11220  // possible.
11221  if (Ov) {
11222  assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
11223  "index (intermediate) result too big");
11224  Offset = Offset.sext(2 * BitWidth);
11225  sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
11226  return;
11227  }
11228 
11229  Offset = ResOffset;
11230 }
11231 
11232 namespace {
11233 
11234 // This is a wrapper class around StringLiteral to support offsetted string
11235 // literals as format strings. It takes the offset into account when returning
11236 // the string and its length or the source locations to display notes correctly.
11237 class FormatStringLiteral {
11238  const StringLiteral *FExpr;
11239  int64_t Offset;
11240 
11241  public:
11242  FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
11243  : FExpr(fexpr), Offset(Offset) {}
11244 
11245  StringRef getString() const {
11246  return FExpr->getString().drop_front(Offset);
11247  }
11248 
11249  unsigned getByteLength() const {
11250  return FExpr->getByteLength() - getCharByteWidth() * Offset;
11251  }
11252 
11253  unsigned getLength() const { return FExpr->getLength() - Offset; }
11254  unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
11255 
11256  StringLiteralKind getKind() const { return FExpr->getKind(); }
11257 
11258  QualType getType() const { return FExpr->getType(); }
11259 
11260  bool isAscii() const { return FExpr->isOrdinary(); }
11261  bool isWide() const { return FExpr->isWide(); }
11262  bool isUTF8() const { return FExpr->isUTF8(); }
11263  bool isUTF16() const { return FExpr->isUTF16(); }
11264  bool isUTF32() const { return FExpr->isUTF32(); }
11265  bool isPascal() const { return FExpr->isPascal(); }
11266 
11267  SourceLocation getLocationOfByte(
11268  unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
11269  const TargetInfo &Target, unsigned *StartToken = nullptr,
11270  unsigned *StartTokenByteOffset = nullptr) const {
11271  return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
11272  StartToken, StartTokenByteOffset);
11273  }
11274 
11275  SourceLocation getBeginLoc() const LLVM_READONLY {
11276  return FExpr->getBeginLoc().getLocWithOffset(Offset);
11277  }
11278 
11279  SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
11280 };
11281 
11282 } // namespace
11283 
11284 static void CheckFormatString(
11285  Sema &S, const FormatStringLiteral *FExpr, const Expr *OrigFormatExpr,
11287  unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type,
11288  bool inFunctionCall, Sema::VariadicCallType CallType,
11289  llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
11290  bool IgnoreStringsWithoutSpecifiers);
11291 
11292 // Determine if an expression is a string literal or constant string.
11293 // If this function returns false on the arguments to a function expecting a
11294 // format string, we will usually need to emit a warning.
11295 // True string literals are then checked by CheckFormatString.
11296 static StringLiteralCheckType
11298  Sema::FormatArgumentPassingKind APK, unsigned format_idx,
11299  unsigned firstDataArg, Sema::FormatStringType Type,
11300  Sema::VariadicCallType CallType, bool InFunctionCall,
11301  llvm::SmallBitVector &CheckedVarArgs,
11302  UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
11303  bool IgnoreStringsWithoutSpecifiers = false) {
11305  return SLCT_NotALiteral;
11306 tryAgain:
11307  assert(Offset.isSigned() && "invalid offset");
11308 
11309  if (E->isTypeDependent() || E->isValueDependent())
11310  return SLCT_NotALiteral;
11311 
11312  E = E->IgnoreParenCasts();
11313 
11315  // Technically -Wformat-nonliteral does not warn about this case.
11316  // The behavior of printf and friends in this case is implementation
11317  // dependent. Ideally if the format string cannot be null then
11318  // it should have a 'nonnull' attribute in the function prototype.
11319  return SLCT_UncheckedLiteral;
11320 
11321  switch (E->getStmtClass()) {
11322  case Stmt::InitListExprClass:
11323  // Handle expressions like {"foobar"}.
11324  if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
11325  return checkFormatStringExpr(S, SLE, Args, APK, format_idx, firstDataArg,
11326  Type, CallType, /*InFunctionCall*/ false,
11327  CheckedVarArgs, UncoveredArg, Offset,
11328  IgnoreStringsWithoutSpecifiers);
11329  }
11330  return SLCT_NotALiteral;
11331  case Stmt::BinaryConditionalOperatorClass:
11332  case Stmt::ConditionalOperatorClass: {
11333  // The expression is a literal if both sub-expressions were, and it was
11334  // completely checked only if both sub-expressions were checked.
11335  const AbstractConditionalOperator *C =
11336  cast<AbstractConditionalOperator>(E);
11337 
11338  // Determine whether it is necessary to check both sub-expressions, for
11339  // example, because the condition expression is a constant that can be
11340  // evaluated at compile time.
11341  bool CheckLeft = true, CheckRight = true;
11342 
11343  bool Cond;
11344  if (C->getCond()->EvaluateAsBooleanCondition(
11345  Cond, S.getASTContext(), S.isConstantEvaluatedContext())) {
11346  if (Cond)
11347  CheckRight = false;
11348  else
11349  CheckLeft = false;
11350  }
11351 
11352  // We need to maintain the offsets for the right and the left hand side
11353  // separately to check if every possible indexed expression is a valid
11354  // string literal. They might have different offsets for different string
11355  // literals in the end.
11356  StringLiteralCheckType Left;
11357  if (!CheckLeft)
11358  Left = SLCT_UncheckedLiteral;
11359  else {
11360  Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, APK, format_idx,
11361  firstDataArg, Type, CallType, InFunctionCall,
11362  CheckedVarArgs, UncoveredArg, Offset,
11363  IgnoreStringsWithoutSpecifiers);
11364  if (Left == SLCT_NotALiteral || !CheckRight) {
11365  return Left;
11366  }
11367  }
11368 
11369  StringLiteralCheckType Right = checkFormatStringExpr(
11370  S, C->getFalseExpr(), Args, APK, format_idx, firstDataArg, Type,
11371  CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
11372  IgnoreStringsWithoutSpecifiers);
11373 
11374  return (CheckLeft && Left < Right) ? Left : Right;
11375  }
11376 
11377  case Stmt::ImplicitCastExprClass:
11378  E = cast<ImplicitCastExpr>(E)->getSubExpr();
11379  goto tryAgain;
11380 
11381  case Stmt::OpaqueValueExprClass:
11382  if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
11383  E = src;
11384  goto tryAgain;
11385  }
11386  return SLCT_NotALiteral;
11387 
11388  case Stmt::PredefinedExprClass:
11389  // While __func__, etc., are technically not string literals, they
11390  // cannot contain format specifiers and thus are not a security
11391  // liability.
11392  return SLCT_UncheckedLiteral;
11393 
11394  case Stmt::DeclRefExprClass: {
11395  const DeclRefExpr *DR = cast<DeclRefExpr>(E);
11396 
11397  // As an exception, do not flag errors for variables binding to
11398  // const string literals.
11399  if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
11400  bool isConstant = false;
11401  QualType T = DR->getType();
11402 
11403  if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
11404  isConstant = AT->getElementType().isConstant(S.Context);
11405  } else if (const PointerType *PT = T->getAs<PointerType>()) {
11406  isConstant = T.isConstant(S.Context) &&
11408  } else if (T->isObjCObjectPointerType()) {
11409  // In ObjC, there is usually no "const ObjectPointer" type,
11410  // so don't check if the pointee type is constant.
11411  isConstant = T.isConstant(S.Context);
11412  }
11413 
11414  if (isConstant) {
11415  if (const Expr *Init = VD->getAnyInitializer()) {
11416  // Look through initializers like const char c[] = { "foo" }
11417  if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
11418  if (InitList->isStringLiteralInit())
11419  Init = InitList->getInit(0)->IgnoreParenImpCasts();
11420  }
11421  return checkFormatStringExpr(
11422  S, Init, Args, APK, format_idx, firstDataArg, Type, CallType,
11423  /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg, Offset);
11424  }
11425  }
11426 
11427  // When the format argument is an argument of this function, and this
11428  // function also has the format attribute, there are several interactions
11429  // for which there shouldn't be a warning. For instance, when calling
11430  // v*printf from a function that has the printf format attribute, we
11431  // should not emit a warning about using `fmt`, even though it's not
11432  // constant, because the arguments have already been checked for the
11433  // caller of `logmessage`:
11434  //
11435  // __attribute__((format(printf, 1, 2)))
11436  // void logmessage(char const *fmt, ...) {
11437  // va_list ap;
11438  // va_start(ap, fmt);
11439  // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
11440  // ...
11441  // }
11442  //
11443  // Another interaction that we need to support is calling a variadic
11444  // format function from a format function that has fixed arguments. For
11445  // instance:
11446  //
11447  // __attribute__((format(printf, 1, 2)))
11448  // void logstring(char const *fmt, char const *str) {
11449  // printf(fmt, str); /* do not emit a warning about "fmt" */
11450  // }
11451  //
11452  // Same (and perhaps more relatably) for the variadic template case:
11453  //
11454  // template<typename... Args>
11455  // __attribute__((format(printf, 1, 2)))
11456  // void log(const char *fmt, Args&&... args) {
11457  // printf(fmt, forward<Args>(args)...);
11458  // /* do not emit a warning about "fmt" */
11459  // }
11460  //
11461  // Due to implementation difficulty, we only check the format, not the
11462  // format arguments, in all cases.
11463  //
11464  if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
11465  if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
11466  for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
11467  bool IsCXXMember = false;
11468  if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
11469  IsCXXMember = MD->isInstance();
11470 
11471  bool IsVariadic = false;
11472  if (const FunctionType *FnTy = D->getFunctionType())
11473  IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
11474  else if (const auto *BD = dyn_cast<BlockDecl>(D))
11475  IsVariadic = BD->isVariadic();
11476  else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
11477  IsVariadic = OMD->isVariadic();
11478 
11479  Sema::FormatStringInfo CallerFSI;
11480  if (Sema::getFormatStringInfo(PVFormat, IsCXXMember, IsVariadic,
11481  &CallerFSI)) {
11482  // We also check if the formats are compatible.
11483  // We can't pass a 'scanf' string to a 'printf' function.
11484  if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx &&
11485  Type == S.GetFormatStringType(PVFormat)) {
11486  // Lastly, check that argument passing kinds transition in a
11487  // way that makes sense:
11488  // from a caller with FAPK_VAList, allow FAPK_VAList
11489  // from a caller with FAPK_Fixed, allow FAPK_Fixed
11490  // from a caller with FAPK_Fixed, allow FAPK_Variadic
11491  // from a caller with FAPK_Variadic, allow FAPK_VAList
11492  switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
11497  return SLCT_UncheckedLiteral;
11498  }
11499  }
11500  }
11501  }
11502  }
11503  }
11504  }
11505 
11506  return SLCT_NotALiteral;
11507  }
11508 
11509  case Stmt::CallExprClass:
11510  case Stmt::CXXMemberCallExprClass: {
11511  const CallExpr *CE = cast<CallExpr>(E);
11512  if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
11513  bool IsFirst = true;
11514  StringLiteralCheckType CommonResult;
11515  for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
11516  const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
11517  StringLiteralCheckType Result = checkFormatStringExpr(
11518  S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType,
11519  InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
11520  IgnoreStringsWithoutSpecifiers);
11521  if (IsFirst) {
11522  CommonResult = Result;
11523  IsFirst = false;
11524  }
11525  }
11526  if (!IsFirst)
11527  return CommonResult;
11528 
11529  if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
11530  unsigned BuiltinID = FD->getBuiltinID();
11531  if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
11532  BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
11533  const Expr *Arg = CE->getArg(0);
11534  return checkFormatStringExpr(
11535  S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType,
11536  InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
11537  IgnoreStringsWithoutSpecifiers);
11538  }
11539  }
11540  }
11541  if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
11542  return checkFormatStringExpr(S, SLE, Args, APK, format_idx, firstDataArg,
11543  Type, CallType, /*InFunctionCall*/ false,
11544  CheckedVarArgs, UncoveredArg, Offset,
11545  IgnoreStringsWithoutSpecifiers);
11546  return SLCT_NotALiteral;
11547  }
11548  case Stmt::ObjCMessageExprClass: {
11549  const auto *ME = cast<ObjCMessageExpr>(E);
11550  if (const auto *MD = ME->getMethodDecl()) {
11551  if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
11552  // As a special case heuristic, if we're using the method -[NSBundle
11553  // localizedStringForKey:value:table:], ignore any key strings that lack
11554  // format specifiers. The idea is that if the key doesn't have any
11555  // format specifiers then its probably just a key to map to the
11556  // localized strings. If it does have format specifiers though, then its
11557  // likely that the text of the key is the format string in the
11558  // programmer's language, and should be checked.
11559  const ObjCInterfaceDecl *IFace;
11560  if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
11561  IFace->getIdentifier()->isStr("NSBundle") &&
11562  MD->getSelector().isKeywordSelector(
11563  {"localizedStringForKey", "value", "table"})) {
11564  IgnoreStringsWithoutSpecifiers = true;
11565  }
11566 
11567  const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
11568  return checkFormatStringExpr(
11569  S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType,
11570  InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
11571  IgnoreStringsWithoutSpecifiers);
11572  }
11573  }
11574 
11575  return SLCT_NotALiteral;
11576  }
11577  case Stmt::ObjCStringLiteralClass:
11578  case Stmt::StringLiteralClass: {
11579  const StringLiteral *StrE = nullptr;
11580 
11581  if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
11582  StrE = ObjCFExpr->getString();
11583  else
11584  StrE = cast<StringLiteral>(E);
11585 
11586  if (StrE) {
11587  if (Offset.isNegative() || Offset > StrE->getLength()) {
11588  // TODO: It would be better to have an explicit warning for out of
11589  // bounds literals.
11590  return SLCT_NotALiteral;
11591  }
11592  FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
11593  CheckFormatString(S, &FStr, E, Args, APK, format_idx, firstDataArg, Type,
11594  InFunctionCall, CallType, CheckedVarArgs, UncoveredArg,
11595  IgnoreStringsWithoutSpecifiers);
11596  return SLCT_CheckedLiteral;
11597  }
11598 
11599  return SLCT_NotALiteral;
11600  }
11601  case Stmt::BinaryOperatorClass: {
11602  const BinaryOperator *BinOp = cast<BinaryOperator>(E);
11603 
11604  // A string literal + an int offset is still a string literal.
11605  if (BinOp->isAdditiveOp()) {
11606  Expr::EvalResult LResult, RResult;
11607 
11608  bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
11609  LResult, S.Context, Expr::SE_NoSideEffects,
11611  bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
11612  RResult, S.Context, Expr::SE_NoSideEffects,
11614 
11615  if (LIsInt != RIsInt) {
11616  BinaryOperatorKind BinOpKind = BinOp->getOpcode();
11617 
11618  if (LIsInt) {
11619  if (BinOpKind == BO_Add) {
11620  sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
11621  E = BinOp->getRHS();
11622  goto tryAgain;
11623  }
11624  } else {
11625  sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
11626  E = BinOp->getLHS();
11627  goto tryAgain;
11628  }
11629  }
11630  }
11631 
11632  return SLCT_NotALiteral;
11633  }
11634  case Stmt::UnaryOperatorClass: {
11635  const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
11636  auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
11637  if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
11638  Expr::EvalResult IndexResult;
11639  if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
11642  sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
11643  /*RHS is int*/ true);
11644  E = ASE->getBase();
11645  goto tryAgain;
11646  }
11647  }
11648 
11649  return SLCT_NotALiteral;
11650  }
11651 
11652  default:
11653  return SLCT_NotALiteral;
11654  }
11655 }
11656 
11657 // If this expression can be evaluated at compile-time,
11658 // check if the result is a StringLiteral and return it
11659 // otherwise return nullptr
11661  const Expr *E) {
11662  Expr::EvalResult Result;
11663  if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
11664  const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
11665  if (isa_and_nonnull<StringLiteral>(LVE))
11666  return LVE;
11667  }
11668  return nullptr;
11669 }
11670 
11672  return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
11673  .Case("scanf", FST_Scanf)
11674  .Cases("printf", "printf0", FST_Printf)
11675  .Cases("NSString", "CFString", FST_NSString)
11676  .Case("strftime", FST_Strftime)
11677  .Case("strfmon", FST_Strfmon)
11678  .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
11679  .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
11680  .Case("os_trace", FST_OSLog)
11681  .Case("os_log", FST_OSLog)
11682  .Default(FST_Unknown);
11683 }
11684 
11685 /// CheckFormatArguments - Check calls to printf and scanf (and similar
11686 /// functions) for correct use of format strings.
11687 /// Returns true if a format string has been fully checked.
11688 bool Sema::CheckFormatArguments(const FormatAttr *Format,
11689  ArrayRef<const Expr *> Args, bool IsCXXMember,
11690  VariadicCallType CallType, SourceLocation Loc,
11691  SourceRange Range,
11692  llvm::SmallBitVector &CheckedVarArgs) {
11693  FormatStringInfo FSI;
11694  if (getFormatStringInfo(Format, IsCXXMember, CallType != VariadicDoesNotApply,
11695  &FSI))
11696  return CheckFormatArguments(Args, FSI.ArgPassingKind, FSI.FormatIdx,
11697  FSI.FirstDataArg, GetFormatStringType(Format),
11698  CallType, Loc, Range, CheckedVarArgs);
11699  return false;
11700 }
11701 
11702 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
11704  unsigned format_idx, unsigned firstDataArg,
11705  FormatStringType Type,
11706  VariadicCallType CallType, SourceLocation Loc,
11707  SourceRange Range,
11708  llvm::SmallBitVector &CheckedVarArgs) {
11709  // CHECK: printf/scanf-like function is called with no format string.
11710  if (format_idx >= Args.size()) {
11711  Diag(Loc, diag::warn_missing_format_string) << Range;
11712  return false;
11713  }
11714 
11715  const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
11716 
11717  // CHECK: format string is not a string literal.
11718  //
11719  // Dynamically generated format strings are difficult to
11720  // automatically vet at compile time. Requiring that format strings
11721  // are string literals: (1) permits the checking of format strings by
11722  // the compiler and thereby (2) can practically remove the source of
11723  // many format string exploits.
11724 
11725  // Format string can be either ObjC string (e.g. @"%d") or
11726  // C string (e.g. "%d")
11727  // ObjC string uses the same format specifiers as C string, so we can use
11728  // the same format string checking logic for both ObjC and C strings.
11729  UncoveredArgHandler UncoveredArg;
11730  StringLiteralCheckType CT = checkFormatStringExpr(
11731  *this, OrigFormatExpr, Args, APK, format_idx, firstDataArg, Type,
11732  CallType,
11733  /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
11734  /*no string offset*/ llvm::APSInt(64, false) = 0);
11735 
11736  // Generate a diagnostic where an uncovered argument is detected.
11737  if (UncoveredArg.hasUncoveredArg()) {
11738  unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
11739  assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
11740  UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
11741  }
11742 
11743  if (CT != SLCT_NotALiteral)
11744  // Literal format string found, check done!
11745  return CT == SLCT_CheckedLiteral;
11746 
11747  // Strftime is particular as it always uses a single 'time' argument,
11748  // so it is safe to pass a non-literal string.
11749  if (Type == FST_Strftime)
11750  return false;
11751 
11752  // Do not emit diag when the string param is a macro expansion and the
11753  // format is either NSString or CFString. This is a hack to prevent
11754  // diag when using the NSLocalizedString and CFCopyLocalizedString macros
11755  // which are usually used in place of NS and CF string literals.
11756  SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
11757  if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
11758  return false;
11759 
11760  // If there are no arguments specified, warn with -Wformat-security, otherwise
11761  // warn only with -Wformat-nonliteral.
11762  if (Args.size() == firstDataArg) {
11763  Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
11764  << OrigFormatExpr->getSourceRange();
11765  switch (Type) {
11766  default:
11767  break;
11768  case FST_Kprintf:
11769  case FST_FreeBSDKPrintf:
11770  case FST_Printf:
11771  Diag(FormatLoc, diag::note_format_security_fixit)
11772  << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
11773  break;
11774  case FST_NSString:
11775  Diag(FormatLoc, diag::note_format_security_fixit)
11776  << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
11777  break;
11778  }
11779  } else {
11780  Diag(FormatLoc, diag::warn_format_nonliteral)
11781  << OrigFormatExpr->getSourceRange();
11782  }
11783  return false;
11784 }
11785 
11786 namespace {
11787 
11788 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
11789 protected:
11790  Sema &S;
11791  const FormatStringLiteral *FExpr;
11792  const Expr *OrigFormatExpr;
11793  const Sema::FormatStringType FSType;
11794  const unsigned FirstDataArg;
11795  const unsigned NumDataArgs;
11796  const char *Beg; // Start of format string.
11797  const Sema::FormatArgumentPassingKind ArgPassingKind;
11799  unsigned FormatIdx;
11800  llvm::SmallBitVector CoveredArgs;
11801  bool usesPositionalArgs = false;
11802  bool atFirstArg = true;
11803  bool inFunctionCall;
11804  Sema::VariadicCallType CallType;
11805  llvm::SmallBitVector &CheckedVarArgs;
11806  UncoveredArgHandler &UncoveredArg;
11807 
11808 public:
11809  CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
11810  const Expr *origFormatExpr,
11811  const Sema::FormatStringType type, unsigned firstDataArg,
11812  unsigned numDataArgs, const char *beg,
11814  ArrayRef<const Expr *> Args, unsigned formatIdx,
11815  bool inFunctionCall, Sema::VariadicCallType callType,
11816  llvm::SmallBitVector &CheckedVarArgs,
11817  UncoveredArgHandler &UncoveredArg)
11818  : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
11819  FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
11820  ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
11821  inFunctionCall(inFunctionCall), CallType(callType),
11822  CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
11823  CoveredArgs.resize(numDataArgs);
11824  CoveredArgs.reset();
11825  }
11826 
11827  void DoneProcessing();
11828 
11829  void HandleIncompleteSpecifier(const char *startSpecifier,
11830  unsigned specifierLen) override;
11831 
11832  void HandleInvalidLengthModifier(
11835  const char *startSpecifier, unsigned specifierLen,
11836  unsigned DiagID);
11837 
11838  void HandleNonStandardLengthModifier(
11840  const char *startSpecifier, unsigned specifierLen);
11841 
11842  void HandleNonStandardConversionSpecifier(
11844  const char *startSpecifier, unsigned specifierLen);
11845 
11846  void HandlePosition(const char *startPos, unsigned posLen) override;
11847 
11848  void HandleInvalidPosition(const char *startSpecifier,
11849  unsigned specifierLen,
11851 
11852  void HandleZeroPosition(const char *startPos, unsigned posLen) override;
11853 
11854  void HandleNullChar(const char *nullCharacter) override;
11855 
11856  template <typename Range>
11857  static void
11858  EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
11859  const PartialDiagnostic &PDiag, SourceLocation StringLoc,
11860  bool IsStringLocation, Range StringRange,
11861  ArrayRef<FixItHint> Fixit = std::nullopt);
11862 
11863 protected:
11864  bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
11865  const char *startSpec,
11866  unsigned specifierLen,
11867  const char *csStart, unsigned csLen);
11868 
11869  void HandlePositionalNonpositionalArgs(SourceLocation Loc,
11870  const char *startSpec,
11871  unsigned specifierLen);
11872 
11873  SourceRange getFormatStringRange();
11874  CharSourceRange getSpecifierRange(const char *startSpecifier,
11875  unsigned specifierLen);
11876  SourceLocation getLocationOfByte(const char *x);
11877 
11878  const Expr *getDataArg(unsigned i) const;
11879 
11880  bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
11882  const char *startSpecifier, unsigned specifierLen,
11883  unsigned argIndex);
11884 
11885  template <typename Range>
11886  void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
11887  bool IsStringLocation, Range StringRange,
11888  ArrayRef<FixItHint> Fixit = std::nullopt);
11889 };
11890 
11891 } // namespace
11892 
11893 SourceRange CheckFormatHandler::getFormatStringRange() {
11894  return OrigFormatExpr->getSourceRange();
11895 }
11896 
11897 CharSourceRange CheckFormatHandler::
11898 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
11899  SourceLocation Start = getLocationOfByte(startSpecifier);
11900  SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
11901 
11902  // Advance the end SourceLocation by one due to half-open ranges.
11903  End = End.getLocWithOffset(1);
11904 
11905  return CharSourceRange::getCharRange(Start, End);
11906 }
11907 
11908 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
11909  return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
11910  S.getLangOpts(), S.Context.getTargetInfo());
11911 }
11912 
11913 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
11914  unsigned specifierLen){
11915  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
11916  getLocationOfByte(startSpecifier),
11917  /*IsStringLocation*/true,
11918  getSpecifierRange(startSpecifier, specifierLen));
11919 }
11920 
11921 void CheckFormatHandler::HandleInvalidLengthModifier(
11924  const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
11925  using namespace analyze_format_string;
11926 
11927  const LengthModifier &LM = FS.getLengthModifier();
11928  CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
11929 
11930  // See if we know how to fix this length modifier.
11931  std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
11932  if (FixedLM) {
11933  EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
11934  getLocationOfByte(LM.getStart()),
11935  /*IsStringLocation*/true,
11936  getSpecifierRange(startSpecifier, specifierLen));
11937 
11938  S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
11939  << FixedLM->toString()
11940  << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
11941 
11942  } else {
11943  FixItHint Hint;
11944  if (DiagID == diag::warn_format_nonsensical_length)
11945  Hint = FixItHint::CreateRemoval(LMRange);
11946 
11947  EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
11948  getLocationOfByte(LM.getStart()),
11949  /*IsStringLocation*/true,
11950  getSpecifierRange(startSpecifier, specifierLen),
11951  Hint);
11952  }
11953 }
11954 
11955 void CheckFormatHandler::HandleNonStandardLengthModifier(
11957  const char *startSpecifier, unsigned specifierLen) {
11958  using namespace analyze_format_string;
11959 
11960  const LengthModifier &LM = FS.getLengthModifier();
11961  CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
11962 
11963  // See if we know how to fix this length modifier.
11964  std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
11965  if (FixedLM) {
11966  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
11967  << LM.toString() << 0,
11968  getLocationOfByte(LM.getStart()),
11969  /*IsStringLocation*/true,
11970  getSpecifierRange(startSpecifier, specifierLen));
11971 
11972  S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
11973  << FixedLM->toString()
11974  << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
11975 
11976  } else {
11977  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
11978  << LM.toString() << 0,
11979  getLocationOfByte(LM.getStart()),
11980  /*IsStringLocation*/true,
11981  getSpecifierRange(startSpecifier, specifierLen));
11982  }
11983 }
11984 
11985 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
11987  const char *startSpecifier, unsigned specifierLen) {
11988  using namespace analyze_format_string;
11989 
11990  // See if we know how to fix this conversion specifier.
11991  std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
11992  if (FixedCS) {
11993  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
11994  << CS.toString() << /*conversion specifier*/1,
11995  getLocationOfByte(CS.getStart()),
11996  /*IsStringLocation*/true,
11997  getSpecifierRange(startSpecifier, specifierLen));
11998 
11999  CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
12000  S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
12001  << FixedCS->toString()
12002  << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
12003  } else {
12004  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
12005  << CS.toString() << /*conversion specifier*/1,
12006  getLocationOfByte(CS.getStart()),
12007  /*IsStringLocation*/true,
12008  getSpecifierRange(startSpecifier, specifierLen));
12009  }
12010 }
12011 
12012 void CheckFormatHandler::HandlePosition(const char *startPos,
12013  unsigned posLen) {
12014  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
12015  getLocationOfByte(startPos),
12016  /*IsStringLocation*/true,
12017  getSpecifierRange(startPos, posLen));
12018 }
12019 
12020 void CheckFormatHandler::HandleInvalidPosition(
12021  const char *startSpecifier, unsigned specifierLen,
12023  EmitFormatDiagnostic(
12024  S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
12025  getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
12026  getSpecifierRange(startSpecifier, specifierLen));
12027 }
12028 
12029 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
12030  unsigned posLen) {
12031  EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
12032  getLocationOfByte(startPos),
12033  /*IsStringLocation*/true,
12034  getSpecifierRange(startPos, posLen));
12035 }
12036 
12037 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
12038  if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
12039  // The presence of a null character is likely an error.
12040  EmitFormatDiagnostic(
12041  S.PDiag(diag::warn_printf_format_string_contains_null_char),
12042  getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
12043  getFormatStringRange());
12044  }
12045 }
12046 
12047 // Note that this may return NULL if there was an error parsing or building
12048 // one of the argument expressions.
12049 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
12050  return Args[FirstDataArg + i];
12051 }
12052 
12053 void CheckFormatHandler::DoneProcessing() {
12054  // Does the number of data arguments exceed the number of
12055  // format conversions in the format string?
12056  if (ArgPassingKind != Sema::FAPK_VAList) {
12057  // Find any arguments that weren't covered.
12058  CoveredArgs.flip();
12059  signed notCoveredArg = CoveredArgs.find_first();
12060  if (notCoveredArg >= 0) {
12061  assert((unsigned)notCoveredArg < NumDataArgs);
12062  UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
12063  } else {
12064  UncoveredArg.setAllCovered();
12065  }
12066  }
12067 }
12068 
12069 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
12070  const Expr *ArgExpr) {
12071  assert(hasUncoveredArg() && !DiagnosticExprs.empty() &&
12072  "Invalid state");
12073 
12074  if (!ArgExpr)
12075  return;
12076 
12077  SourceLocation Loc = ArgExpr->getBeginLoc();
12078 
12079  if (S.getSourceManager().isInSystemMacro(Loc))
12080  return;
12081 
12082  PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
12083  for (auto E : DiagnosticExprs)
12084  PDiag << E->getSourceRange();
12085 
12086  CheckFormatHandler::EmitFormatDiagnostic(
12087  S, IsFunctionCall, DiagnosticExprs[0],
12088  PDiag, Loc, /*IsStringLocation*/false,
12089  DiagnosticExprs[0]->getSourceRange());
12090 }
12091 
12092 bool
12093 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
12094  SourceLocation Loc,
12095  const char *startSpec,
12096  unsigned specifierLen,
12097  const char *csStart,
12098  unsigned csLen) {
12099  bool keepGoing = true;
12100  if (argIndex < NumDataArgs) {
12101  // Consider the argument coverered, even though the specifier doesn't
12102  // make sense.
12103  CoveredArgs.set(argIndex);
12104  }
12105  else {
12106  // If argIndex exceeds the number of data arguments we
12107  // don't issue a warning because that is just a cascade of warnings (and
12108  // they may have intended '%%' anyway). We don't want to continue processing
12109  // the format string after this point, however, as we will like just get
12110  // gibberish when trying to match arguments.
12111  keepGoing = false;
12112  }
12113 
12114  StringRef Specifier(csStart, csLen);
12115 
12116  // If the specifier in non-printable, it could be the first byte of a UTF-8
12117  // sequence. In that case, print the UTF-8 code point. If not, print the byte
12118  // hex value.
12119  std::string CodePointStr;
12120  if (!llvm::sys::locale::isPrint(*csStart)) {
12121  llvm::UTF32 CodePoint;
12122  const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
12123  const llvm::UTF8 *E =
12124  reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
12125  llvm::ConversionResult Result =
12126  llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
12127 
12128  if (Result != llvm::conversionOK) {
12129  unsigned char FirstChar = *csStart;
12130  CodePoint = (llvm::UTF32)FirstChar;
12131  }
12132 
12133  llvm::raw_string_ostream OS(CodePointStr);
12134  if (CodePoint < 256)
12135  OS << "\\x" << llvm::format("%02x", CodePoint);
12136  else if (CodePoint <= 0xFFFF)
12137  OS << "\\u" << llvm::format("%04x", CodePoint);
12138  else
12139  OS << "\\U" << llvm::format("%08x", CodePoint);
12140  OS.flush();
12141  Specifier = CodePointStr;
12142  }
12143 
12144  EmitFormatDiagnostic(
12145  S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
12146  /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
12147 
12148  return keepGoing;
12149 }
12150 
12151 void
12152 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
12153  const char *startSpec,
12154  unsigned specifierLen) {
12155  EmitFormatDiagnostic(
12156  S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
12157  Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
12158 }
12159 
12160 bool
12161 CheckFormatHandler::CheckNumArgs(
12164  const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
12165 
12166  if (argIndex >= NumDataArgs) {
12167  PartialDiagnostic PDiag = FS.usesPositionalArg()
12168  ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
12169  << (argIndex+1) << NumDataArgs)
12170  : S.PDiag(diag::warn_printf_insufficient_data_args);
12171  EmitFormatDiagnostic(
12172  PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
12173  getSpecifierRange(startSpecifier, specifierLen));
12174 
12175  // Since more arguments than conversion tokens are given, by extension
12176  // all arguments are covered, so mark this as so.
12177  UncoveredArg.setAllCovered();
12178  return false;
12179  }
12180  return true;
12181 }
12182 
12183 template<typename Range>
12184 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
12185  SourceLocation Loc,
12186  bool IsStringLocation,
12187  Range StringRange,
12189  EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
12190  Loc, IsStringLocation, StringRange, FixIt);
12191 }
12192 
12193 /// If the format string is not within the function call, emit a note
12194 /// so that the function call and string are in diagnostic messages.
12195 ///
12196 /// \param InFunctionCall if true, the format string is within the function
12197 /// call and only one diagnostic message will be produced. Otherwise, an
12198 /// extra note will be emitted pointing to location of the format string.
12199 ///
12200 /// \param ArgumentExpr the expression that is passed as the format string
12201 /// argument in the function call. Used for getting locations when two
12202 /// diagnostics are emitted.
12203 ///
12204 /// \param PDiag the callee should already have provided any strings for the
12205 /// diagnostic message. This function only adds locations and fixits
12206 /// to diagnostics.
12207 ///
12208 /// \param Loc primary location for diagnostic. If two diagnostics are
12209 /// required, one will be at Loc and a new SourceLocation will be created for
12210 /// the other one.
12211 ///
12212 /// \param IsStringLocation if true, Loc points to the format string should be
12213 /// used for the note. Otherwise, Loc points to the argument list and will
12214 /// be used with PDiag.
12215 ///
12216 /// \param StringRange some or all of the string to highlight. This is
12217 /// templated so it can accept either a CharSourceRange or a SourceRange.
12218 ///
12219 /// \param FixIt optional fix it hint for the format string.
12220 template <typename Range>
12221 void CheckFormatHandler::EmitFormatDiagnostic(
12222  Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
12223  const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
12224  Range StringRange, ArrayRef<FixItHint> FixIt) {
12225  if (InFunctionCall) {
12226  const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
12227  D << StringRange;
12228  D << FixIt;
12229  } else {
12230  S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
12231  << ArgumentExpr->getSourceRange();
12232 
12233  const Sema::SemaDiagnosticBuilder &Note =
12234  S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
12235  diag::note_format_string_defined);
12236 
12237  Note << StringRange;
12238  Note << FixIt;
12239  }
12240 }
12241 
12242 //===--- CHECK: Printf format string checking -----------------------------===//
12243 
12244 namespace {
12245 
12246 class CheckPrintfHandler : public CheckFormatHandler {
12247 public:
12248  CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
12249  const Expr *origFormatExpr,
12250  const Sema::FormatStringType type, unsigned firstDataArg,
12251  unsigned numDataArgs, bool isObjC, const char *beg,
12253  ArrayRef<const Expr *> Args, unsigned formatIdx,
12254  bool inFunctionCall, Sema::VariadicCallType CallType,
12255  llvm::SmallBitVector &CheckedVarArgs,
12256  UncoveredArgHandler &UncoveredArg)
12257  : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
12258  numDataArgs, beg, APK, Args, formatIdx,
12259  inFunctionCall, CallType, CheckedVarArgs,
12260  UncoveredArg) {}
12261 
12262  bool isObjCContext() const { return FSType == Sema::FST_NSString; }
12263 
12264  /// Returns true if '%@' specifiers are allowed in the format string.
12265  bool allowsObjCArg() const {
12266  return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
12267  FSType == Sema::FST_OSTrace;
12268  }
12269 
12270  bool HandleInvalidPrintfConversionSpecifier(
12272  const char *startSpecifier,
12273  unsigned specifierLen) override;
12274 
12275  void handleInvalidMaskType(StringRef MaskType) override;
12276 
12277  bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
12278  const char *startSpecifier, unsigned specifierLen,
12279  const TargetInfo &Target) override;
12280  bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
12281  const char *StartSpecifier,
12282  unsigned SpecifierLen,
12283  const Expr *E);
12284 
12285  bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
12286  const char *startSpecifier, unsigned specifierLen);
12287  void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
12288  const analyze_printf::OptionalAmount &Amt,
12289  unsigned type,
12290  const char *startSpecifier, unsigned specifierLen);
12291  void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
12292  const analyze_printf::OptionalFlag &flag,
12293  const char *startSpecifier, unsigned specifierLen);
12294  void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
12295  const analyze_printf::OptionalFlag &ignoredFlag,
12296  const analyze_printf::OptionalFlag &flag,
12297  const char *startSpecifier, unsigned specifierLen);
12298  bool checkForCStrMembers(const analyze_printf::ArgType &AT,
12299  const Expr *E);
12300 
12301  void HandleEmptyObjCModifierFlag(const char *startFlag,
12302  unsigned flagLen) override;
12303 
12304  void HandleInvalidObjCModifierFlag(const char *startFlag,
12305  unsigned flagLen) override;
12306 
12307  void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
12308  const char *flagsEnd,
12309  const char *conversionPosition)
12310  override;
12311 };
12312 
12313 } // namespace
12314 
12315 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
12317  const char *startSpecifier,
12318  unsigned specifierLen) {
12320  FS.getConversionSpecifier();
12321 
12322  return HandleInvalidConversionSpecifier(FS.getArgIndex(),
12323  getLocationOfByte(CS.getStart()),
12324  startSpecifier, specifierLen,
12325  CS.getStart(), CS.getLength());
12326 }
12327 
12328 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
12329  S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
12330 }
12331 
12332 bool CheckPrintfHandler::HandleAmount(
12333  const analyze_format_string::OptionalAmount &Amt, unsigned k,
12334  const char *startSpecifier, unsigned specifierLen) {
12335  if (Amt.hasDataArgument()) {
12336  if (ArgPassingKind != Sema::FAPK_VAList) {
12337  unsigned argIndex = Amt.getArgIndex();
12338  if (argIndex >= NumDataArgs) {
12339  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
12340  << k,
12341  getLocationOfByte(Amt.getStart()),
12342  /*IsStringLocation*/ true,
12343  getSpecifierRange(startSpecifier, specifierLen));
12344  // Don't do any more checking. We will just emit
12345  // spurious errors.
12346  return false;
12347  }
12348 
12349  // Type check the data argument. It should be an 'int'.
12350  // Although not in conformance with C99, we also allow the argument to be
12351  // an 'unsigned int' as that is a reasonably safe case. GCC also
12352  // doesn't emit a warning for that case.
12353  CoveredArgs.set(argIndex);
12354  const Expr *Arg = getDataArg(argIndex);
12355  if (!Arg)
12356  return false;
12357 
12358  QualType T = Arg->getType();
12359 
12360  const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
12361  assert(AT.isValid());
12362 
12363  if (!AT.matchesType(S.Context, T)) {
12364  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
12365  << k << AT.getRepresentativeTypeName(S.Context)
12366  << T << Arg->getSourceRange(),
12367  getLocationOfByte(Amt.getStart()),
12368  /*IsStringLocation*/true,
12369  getSpecifierRange(startSpecifier, specifierLen));
12370  // Don't do any more checking. We will just emit
12371  // spurious errors.
12372  return false;
12373  }
12374  }
12375  }
12376  return true;
12377 }
12378 
12379 void CheckPrintfHandler::HandleInvalidAmount(
12381  const analyze_printf::OptionalAmount &Amt,
12382  unsigned type,
12383  const char *startSpecifier,
12384  unsigned specifierLen) {
12386  FS.getConversionSpecifier();
12387 
12388  FixItHint fixit =
12389  Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
12390  ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
12391  Amt.getConstantLength()))
12392  : FixItHint();
12393 
12394  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
12395  << type << CS.toString(),
12396  getLocationOfByte(Amt.getStart()),
12397  /*IsStringLocation*/true,
12398  getSpecifierRange(startSpecifier, specifierLen),
12399  fixit);
12400 }
12401 
12402 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
12403  const analyze_printf::OptionalFlag &flag,
12404  const char *startSpecifier,
12405  unsigned specifierLen) {
12406  // Warn about pointless flag with a fixit removal.
12408  FS.getConversionSpecifier();
12409  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
12410  << flag.toString() << CS.toString(),
12411  getLocationOfByte(flag.getPosition()),
12412  /*IsStringLocation*/true,
12413  getSpecifierRange(startSpecifier, specifierLen),
12415  getSpecifierRange(flag.getPosition(), 1)));
12416 }
12417 
12418 void CheckPrintfHandler::HandleIgnoredFlag(
12420  const analyze_printf::OptionalFlag &ignoredFlag,
12421  const analyze_printf::OptionalFlag &flag,
12422  const char *startSpecifier,
12423  unsigned specifierLen) {
12424  // Warn about ignored flag with a fixit removal.
12425  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
12426  << ignoredFlag.toString() << flag.toString(),
12427  getLocationOfByte(ignoredFlag.getPosition()),
12428  /*IsStringLocation*/true,
12429  getSpecifierRange(startSpecifier, specifierLen),
12431  getSpecifierRange(ignoredFlag.getPosition(), 1)));
12432 }
12433 
12434 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
12435  unsigned flagLen) {
12436  // Warn about an empty flag.
12437  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
12438  getLocationOfByte(startFlag),
12439  /*IsStringLocation*/true,
12440  getSpecifierRange(startFlag, flagLen));
12441 }
12442 
12443 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
12444  unsigned flagLen) {
12445  // Warn about an invalid flag.
12446  auto Range = getSpecifierRange(startFlag, flagLen);
12447  StringRef flag(startFlag, flagLen);
12448  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
12449  getLocationOfByte(startFlag),
12450  /*IsStringLocation*/true,
12451  Range, FixItHint::CreateRemoval(Range));
12452 }
12453 
12454 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
12455  const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
12456  // Warn about using '[...]' without a '@' conversion.
12457  auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
12458  auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
12459  EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
12460  getLocationOfByte(conversionPosition),
12461  /*IsStringLocation*/true,
12462  Range, FixItHint::CreateRemoval(Range));
12463 }
12464 
12465 // Determines if the specified is a C++ class or struct containing
12466 // a member with the specified name and kind (e.g. a CXXMethodDecl named
12467 // "c_str()").
12468 template<typename MemberKind>
12470 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
12471  const RecordType *RT = Ty->getAs<RecordType>();
12473 
12474  if (!RT)
12475  return Results;
12476  const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
12477  if (!RD || !RD->getDefinition())
12478  return Results;
12479 
12480  LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
12482  R.suppressDiagnostics();
12483 
12484  // We just need to include all members of the right kind turned up by the
12485  // filter, at this point.
12486  if (S.LookupQualifiedName(R, RT->getDecl()))
12487  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12488  NamedDecl *decl = (*I)->getUnderlyingDecl();
12489  if (MemberKind *FK = dyn_cast<MemberKind>(decl))
12490  Results.insert(FK);
12491  }
12492  return Results;
12493 }
12494 
12495 /// Check if we could call '.c_str()' on an object.
12496 ///
12497 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
12498 /// allow the call, or if it would be ambiguous).
12499 bool Sema::hasCStrMethod(const Expr *E) {
12500  using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
12501 
12502  MethodSet Results =
12503  CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
12504  for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
12505  MI != ME; ++MI)
12506  if ((*MI)->getMinRequiredArguments() == 0)
12507  return true;
12508  return false;
12509 }
12510 
12511 // Check if a (w)string was passed when a (w)char* was needed, and offer a
12512 // better diagnostic if so. AT is assumed to be valid.
12513 // Returns true when a c_str() conversion method is found.
12514 bool CheckPrintfHandler::checkForCStrMembers(
12515  const analyze_printf::ArgType &AT, const Expr *E) {
12516  using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
12517 
12518  MethodSet Results =
12519  CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
12520 
12521  for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
12522  MI != ME; ++MI) {
12523  const CXXMethodDecl *Method = *MI;
12524  if (Method->getMinRequiredArguments() == 0 &&
12525  AT.matchesType(S.Context, Method->getReturnType())) {
12526  // FIXME: Suggest parens if the expression needs them.
12527  SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
12528  S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
12529  << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
12530  return true;
12531  }
12532  }
12533 
12534  return false;
12535 }
12536 
12537 bool CheckPrintfHandler::HandlePrintfSpecifier(
12538  const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
12539  unsigned specifierLen, const TargetInfo &Target) {
12540  using namespace analyze_format_string;
12541  using namespace analyze_printf;
12542 
12543  const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
12544 
12545  if (FS.consumesDataArgument()) {
12546  if (atFirstArg) {
12547  atFirstArg = false;
12548  usesPositionalArgs = FS.usesPositionalArg();
12549  }
12550  else if (usesPositionalArgs != FS.usesPositionalArg()) {
12551  HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
12552  startSpecifier, specifierLen);
12553  return false;
12554  }
12555  }
12556 
12557  // First check if the field width, precision, and conversion specifier
12558  // have matching data arguments.
12559  if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
12560  startSpecifier, specifierLen)) {
12561  return false;
12562  }
12563 
12564  if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
12565  startSpecifier, specifierLen)) {
12566  return false;
12567  }
12568 
12569  if (!CS.consumesDataArgument()) {
12570  // FIXME: Technically specifying a precision or field width here
12571  // makes no sense. Worth issuing a warning at some point.
12572  return true;
12573  }
12574 
12575  // Consume the argument.
12576  unsigned argIndex = FS.getArgIndex();
12577  if (argIndex < NumDataArgs) {
12578  // The check to see if the argIndex is valid will come later.
12579  // We set the bit here because we may exit early from this
12580  // function if we encounter some other error.
12581  CoveredArgs.set(argIndex);
12582  }
12583 
12584  // FreeBSD kernel extensions.
12585  if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
12586  CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
12587  // We need at least two arguments.
12588  if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
12589  return false;
12590 
12591  // Claim the second argument.
12592  CoveredArgs.set(argIndex + 1);
12593 
12594  // Type check the first argument (int for %b, pointer for %D)
12595  const Expr *Ex = getDataArg(argIndex);
12596  const analyze_printf::ArgType &AT =
12597  (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
12598  ArgType(S.Context.IntTy) : ArgType::CPointerTy;
12599  if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
12600  EmitFormatDiagnostic(
12601  S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
12602  << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
12603  << false << Ex->getSourceRange(),
12604  Ex->getBeginLoc(), /*IsStringLocation*/ false,
12605  getSpecifierRange(startSpecifier, specifierLen));
12606 
12607  // Type check the second argument (char * for both %b and %D)
12608  Ex = getDataArg(argIndex + 1);
12609  const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
12610  if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
12611  EmitFormatDiagnostic(
12612  S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
12613  << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
12614  << false << Ex->getSourceRange(),
12615  Ex->getBeginLoc(), /*IsStringLocation*/ false,
12616  getSpecifierRange(startSpecifier, specifierLen));
12617 
12618  return true;
12619  }
12620 
12621  // Check for using an Objective-C specific conversion specifier
12622  // in a non-ObjC literal.
12623  if (!allowsObjCArg() && CS.isObjCArg()) {
12624  return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
12625  specifierLen);
12626  }
12627 
12628  // %P can only be used with os_log.
12629  if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
12630  return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
12631  specifierLen);
12632  }
12633 
12634  // %n is not allowed with os_log.
12635  if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
12636  EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
12637  getLocationOfByte(CS.getStart()),
12638  /*IsStringLocation*/ false,
12639  getSpecifierRange(startSpecifier, specifierLen));
12640 
12641  return true;
12642  }
12643 
12644  // Only scalars are allowed for os_trace.
12645  if (FSType == Sema::FST_OSTrace &&
12646  (CS.getKind() == ConversionSpecifier::PArg ||
12647  CS.getKind() == ConversionSpecifier::sArg ||
12648  CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
12649  return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
12650  specifierLen);
12651  }
12652 
12653  // Check for use of public/private annotation outside of os_log().
12654  if (FSType != Sema::FST_OSLog) {
12655  if (FS.isPublic().isSet()) {
12656  EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
12657  << "public",
12658  getLocationOfByte(FS.isPublic().getPosition()),
12659  /*IsStringLocation*/ false,
12660  getSpecifierRange(startSpecifier, specifierLen));
12661  }
12662  if (FS.isPrivate().isSet()) {
12663  EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
12664  << "private",
12665  getLocationOfByte(FS.isPrivate().getPosition()),
12666  /*IsStringLocation*/ false,
12667  getSpecifierRange(startSpecifier, specifierLen));
12668  }
12669  }
12670 
12671  const llvm::Triple &Triple = Target.getTriple();
12672  if (CS.getKind() == ConversionSpecifier::nArg &&
12673  (Triple.isAndroid() || Triple.isOSFuchsia())) {
12674  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
12675  getLocationOfByte(CS.getStart()),
12676  /*IsStringLocation*/ false,
12677  getSpecifierRange(startSpecifier, specifierLen));
12678  }
12679 
12680  // Check for invalid use of field width
12681  if (!FS.hasValidFieldWidth()) {
12682  HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
12683  startSpecifier, specifierLen);
12684  }
12685 
12686  // Check for invalid use of precision
12687  if (!FS.hasValidPrecision()) {
12688  HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
12689  startSpecifier, specifierLen);
12690  }
12691 
12692  // Precision is mandatory for %P specifier.
12693  if (CS.getKind() == ConversionSpecifier::PArg &&
12694  FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
12695  EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
12696  getLocationOfByte(startSpecifier),
12697  /*IsStringLocation*/ false,
12698  getSpecifierRange(startSpecifier, specifierLen));
12699  }
12700 
12701  // Check each flag does not conflict with any other component.
12702  if (!FS.hasValidThousandsGroupingPrefix())
12703  HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
12704  if (!FS.hasValidLeadingZeros())
12705  HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
12706  if (!FS.hasValidPlusPrefix())
12707  HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
12708  if (!FS.hasValidSpacePrefix())
12709  HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
12710  if (!FS.hasValidAlternativeForm())
12711  HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
12712  if (!FS.hasValidLeftJustified())
12713  HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
12714 
12715  // Check that flags are not ignored by another flag
12716  if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
12717  HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
12718  startSpecifier, specifierLen);
12719  if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
12720  HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
12721  startSpecifier, specifierLen);
12722 
12723  // Check the length modifier is valid with the given conversion specifier.
12724  if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
12725  S.getLangOpts()))
12726  HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
12727  diag::warn_format_nonsensical_length);
12728  else if (!FS.hasStandardLengthModifier())
12729  HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
12730  else if (!FS.hasStandardLengthConversionCombination())
12731  HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
12732  diag::warn_format_non_standard_conversion_spec);
12733 
12734  if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
12735  HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
12736 
12737  // The remaining checks depend on the data arguments.
12738  if (ArgPassingKind == Sema::FAPK_VAList)
12739  return true;
12740 
12741  if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
12742  return false;
12743 
12744  const Expr *Arg = getDataArg(argIndex);
12745  if (!Arg)
12746  return true;
12747 
12748  return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
12749 }
12750 
12751 static bool requiresParensToAddCast(const Expr *E) {
12752  // FIXME: We should have a general way to reason about operator
12753  // precedence and whether parens are actually needed here.
12754  // Take care of a few common cases where they aren't.
12755  const Expr *Inside = E->IgnoreImpCasts();
12756  if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
12757  Inside = POE->getSyntacticForm()->IgnoreImpCasts();
12758 
12759  switch (Inside->getStmtClass()) {
12760  case Stmt::ArraySubscriptExprClass:
12761  case Stmt::CallExprClass:
12762  case Stmt::CharacterLiteralClass:
12763  case Stmt::CXXBoolLiteralExprClass:
12764  case Stmt::DeclRefExprClass:
12765  case Stmt::FloatingLiteralClass:
12766  case Stmt::IntegerLiteralClass:
12767  case Stmt::MemberExprClass:
12768  case Stmt::ObjCArrayLiteralClass:
12769  case Stmt::ObjCBoolLiteralExprClass:
12770  case Stmt::ObjCBoxedExprClass:
12771  case Stmt::ObjCDictionaryLiteralClass:
12772  case Stmt::ObjCEncodeExprClass:
12773  case Stmt::ObjCIvarRefExprClass:
12774  case Stmt::ObjCMessageExprClass:
12775  case Stmt::ObjCPropertyRefExprClass:
12776  case Stmt::ObjCStringLiteralClass:
12777  case Stmt::ObjCSubscriptRefExprClass:
12778  case Stmt::ParenExprClass:
12779  case Stmt::StringLiteralClass:
12780  case Stmt::UnaryOperatorClass:
12781  return false;
12782  default:
12783  return true;
12784  }
12785 }
12786 
12787 static std::pair<QualType, StringRef>
12789  QualType IntendedTy,
12790  const Expr *E) {
12791  // Use a 'while' to peel off layers of typedefs.
12792  QualType TyTy = IntendedTy;
12793  while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
12794  StringRef Name = UserTy->getDecl()->getName();
12795  QualType CastTy = llvm::StringSwitch<QualType>(Name)
12796  .Case("CFIndex", Context.getNSIntegerType())
12797  .Case("NSInteger", Context.getNSIntegerType())
12798  .Case("NSUInteger", Context.getNSUIntegerType())
12799  .Case("SInt32", Context.IntTy)
12800  .Case("UInt32", Context.UnsignedIntTy)
12801  .Default(QualType());
12802 
12803  if (!CastTy.isNull())
12804  return std::make_pair(CastTy, Name);
12805 
12806  TyTy = UserTy->desugar();
12807  }
12808 
12809  // Strip parens if necessary.
12810  if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
12811  return shouldNotPrintDirectly(Context,
12812  PE->getSubExpr()->getType(),
12813  PE->getSubExpr());
12814 
12815  // If this is a conditional expression, then its result type is constructed
12816  // via usual arithmetic conversions and thus there might be no necessary
12817  // typedef sugar there. Recurse to operands to check for NSInteger &
12818  // Co. usage condition.
12819  if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12820  QualType TrueTy, FalseTy;
12821  StringRef TrueName, FalseName;
12822 
12823  std::tie(TrueTy, TrueName) =
12824  shouldNotPrintDirectly(Context,
12825  CO->getTrueExpr()->getType(),
12826  CO->getTrueExpr());
12827  std::tie(FalseTy, FalseName) =
12828  shouldNotPrintDirectly(Context,
12829  CO->getFalseExpr()->getType(),
12830  CO->getFalseExpr());
12831 
12832  if (TrueTy == FalseTy)
12833  return std::make_pair(TrueTy, TrueName);
12834  else if (TrueTy.isNull())
12835  return std::make_pair(FalseTy, FalseName);
12836  else if (FalseTy.isNull())
12837  return std::make_pair(TrueTy, TrueName);
12838  }
12839 
12840  return std::make_pair(QualType(), StringRef());
12841 }
12842 
12843 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
12844 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
12845 /// type do not count.
12846 static bool
12848  QualType From = ICE->getSubExpr()->getType();
12849  QualType To = ICE->getType();
12850  // It's an integer promotion if the destination type is the promoted
12851  // source type.
12852  if (ICE->getCastKind() == CK_IntegralCast &&
12853  S.Context.isPromotableIntegerType(From) &&
12854  S.Context.getPromotedIntegerType(From) == To)
12855  return true;
12856  // Look through vector types, since we do default argument promotion for
12857  // those in OpenCL.
12858  if (const auto *VecTy = From->getAs<ExtVectorType>())
12859  From = VecTy->getElementType();
12860  if (const auto *VecTy = To->getAs<ExtVectorType>())
12861  To = VecTy->getElementType();
12862  // It's a floating promotion if the source type is a lower rank.
12863  return ICE->getCastKind() == CK_FloatingCast &&
12864  S.Context.getFloatingTypeOrder(From, To) < 0;
12865 }
12866 
12869  DiagnosticsEngine &Diags, SourceLocation Loc) {
12871  Match =
12872  Diags.isIgnored(
12873  diag::warn_format_conversion_argument_type_mismatch_signedness, Loc)
12876  }
12877  return Match;
12878 }
12879 
12880 bool
12881 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
12882  const char *StartSpecifier,
12883  unsigned SpecifierLen,
12884  const Expr *E) {
12885  using namespace analyze_format_string;
12886  using namespace analyze_printf;
12887 
12888  // Now type check the data expression that matches the
12889  // format specifier.
12890  const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
12891  if (!AT.isValid())
12892  return true;
12893 
12894  QualType ExprTy = E->getType();
12895  while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
12896  ExprTy = TET->getUnderlyingExpr()->getType();
12897  }
12898 
12899  // When using the format attribute in C++, you can receive a function or an
12900  // array that will necessarily decay to a pointer when passed to the final
12901  // format consumer. Apply decay before type comparison.
12902  if (ExprTy->canDecayToPointerType())
12903  ExprTy = S.Context.getDecayedType(ExprTy);
12904 
12905  // Diagnose attempts to print a boolean value as a character. Unlike other
12906  // -Wformat diagnostics, this is fine from a type perspective, but it still
12907  // doesn't make sense.
12908  if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
12910  const CharSourceRange &CSR =
12911  getSpecifierRange(StartSpecifier, SpecifierLen);
12912  SmallString<4> FSString;
12913  llvm::raw_svector_ostream os(FSString);
12914  FS.toString(os);
12915  EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
12916  << FSString,
12917  E->getExprLoc(), false, CSR);
12918  return true;
12919  }
12920 
12921  ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
12922  ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
12923  ArgType::MatchKind OrigMatch = Match;
12924 
12925  Match = handleFormatSignedness(Match, S.getDiagnostics(), E->getExprLoc());
12926  if (Match == ArgType::Match)
12927  return true;
12928 
12929  // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
12930  assert(Match != ArgType::NoMatchPromotionTypeConfusion);
12931 
12932  // Look through argument promotions for our error message's reported type.
12933  // This includes the integral and floating promotions, but excludes array
12934  // and function pointer decay (seeing that an argument intended to be a
12935  // string has type 'char [6]' is probably more confusing than 'char *') and
12936  // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
12937  if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12938  if (isArithmeticArgumentPromotion(S, ICE)) {
12939  E = ICE->getSubExpr();
12940  ExprTy = E->getType();
12941 
12942  // Check if we didn't match because of an implicit cast from a 'char'
12943  // or 'short' to an 'int'. This is done because printf is a varargs
12944  // function.
12945  if (ICE->getType() == S.Context.IntTy ||
12946  ICE->getType() == S.Context.UnsignedIntTy) {
12947  // All further checking is done on the subexpression
12948  ImplicitMatch = AT.matchesType(S.Context, ExprTy);
12949  if (OrigMatch == ArgType::NoMatchSignedness &&
12950  ImplicitMatch != ArgType::NoMatchSignedness)
12951  // If the original match was a signedness match this match on the
12952  // implicit cast type also need to be signedness match otherwise we
12953  // might introduce new unexpected warnings from -Wformat-signedness.
12954  return true;
12955  ImplicitMatch = handleFormatSignedness(
12956  ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
12957  if (ImplicitMatch == ArgType::Match)
12958  return true;
12959  }
12960  }
12961  } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
12962  // Special case for 'a', which has type 'int' in C.
12963  // Note, however, that we do /not/ want to treat multibyte constants like
12964  // 'MooV' as characters! This form is deprecated but still exists. In
12965  // addition, don't treat expressions as of type 'char' if one byte length
12966  // modifier is provided.
12967  if (ExprTy == S.Context.IntTy &&
12968  FS.getLengthModifier().getKind() != LengthModifier::AsChar)
12969  if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
12970  ExprTy = S.Context.CharTy;
12971  // To improve check results, we consider a character literal in C
12972  // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
12973  // more likely a type confusion situation, so we will suggest to
12974  // use '%hhd' instead by discarding the MatchPromotion.
12975  if (Match == ArgType::MatchPromotion)
12976  Match = ArgType::NoMatch;
12977  }
12978  }
12979  if (Match == ArgType::MatchPromotion) {
12980  // WG14 N2562 only clarified promotions in *printf
12981  // For NSLog in ObjC, just preserve -Wformat behavior
12982  if (!S.getLangOpts().ObjC &&
12983  ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
12984  ImplicitMatch != ArgType::NoMatchTypeConfusion)
12985  return true;
12986  Match = ArgType::NoMatch;
12987  }
12988  if (ImplicitMatch == ArgType::NoMatchPedantic ||
12989  ImplicitMatch == ArgType::NoMatchTypeConfusion)
12990  Match = ImplicitMatch;
12991  assert(Match != ArgType::MatchPromotion);
12992 
12993  // Look through unscoped enums to their underlying type.
12994  bool IsEnum = false;
12995  bool IsScopedEnum = false;
12996  QualType IntendedTy = ExprTy;
12997  if (auto EnumTy = ExprTy->getAs<EnumType>()) {
12998  IntendedTy = EnumTy->getDecl()->getIntegerType();
12999  if (EnumTy->isUnscopedEnumerationType()) {
13000  ExprTy = IntendedTy;
13001  // This controls whether we're talking about the underlying type or not,
13002  // which we only want to do when it's an unscoped enum.
13003  IsEnum = true;
13004  } else {
13005  IsScopedEnum = true;
13006  }
13007  }
13008 
13009  // %C in an Objective-C context prints a unichar, not a wchar_t.
13010  // If the argument is an integer of some kind, believe the %C and suggest
13011  // a cast instead of changing the conversion specifier.
13012  if (isObjCContext() &&
13013  FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
13014  if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
13015  !ExprTy->isCharType()) {
13016  // 'unichar' is defined as a typedef of unsigned short, but we should
13017  // prefer using the typedef if it is visible.
13018  IntendedTy = S.Context.UnsignedShortTy;
13019 
13020  // While we are here, check if the value is an IntegerLiteral that happens
13021  // to be within the valid range.
13022  if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
13023  const llvm::APInt &V = IL->getValue();
13024  if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
13025  return true;
13026  }
13027 
13028  LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
13030  if (S.LookupName(Result, S.getCurScope())) {
13031  NamedDecl *ND = Result.getFoundDecl();
13032  if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
13033  if (TD->getUnderlyingType() == IntendedTy)
13034  IntendedTy = S.Context.getTypedefType(TD);
13035  }
13036  }
13037  }
13038 
13039  // Special-case some of Darwin's platform-independence types by suggesting
13040  // casts to primitive types that are known to be large enough.
13041  bool ShouldNotPrintDirectly = false; StringRef CastTyName;
13042  if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
13043  QualType CastTy;
13044  std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
13045  if (!CastTy.isNull()) {
13046  // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
13047  // (long in ASTContext). Only complain to pedants or when they're the
13048  // underlying type of a scoped enum (which always needs a cast).
13049  if (!IsScopedEnum &&
13050  (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
13051  (AT.isSizeT() || AT.isPtrdiffT()) &&
13052  AT.matchesType(S.Context, CastTy))
13053  Match = ArgType::NoMatchPedantic;
13054  IntendedTy = CastTy;
13055  ShouldNotPrintDirectly = true;
13056  }
13057  }
13058 
13059  // We may be able to offer a FixItHint if it is a supported type.
13060  PrintfSpecifier fixedFS = FS;
13061  bool Success =
13062  fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
13063 
13064  if (Success) {
13065  // Get the fix string from the fixed format specifier
13066  SmallString<16> buf;
13067  llvm::raw_svector_ostream os(buf);
13068  fixedFS.toString(os);
13069 
13070  CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
13071 
13072  if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
13073  unsigned Diag;
13074  switch (Match) {
13075  case ArgType::Match:
13076  case ArgType::MatchPromotion:
13077  case ArgType::NoMatchPromotionTypeConfusion:
13078  case ArgType::NoMatchSignedness:
13079  llvm_unreachable("expected non-matching");
13080  case ArgType::NoMatchPedantic:
13081  Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
13082  break;
13083  case ArgType::NoMatchTypeConfusion:
13084  Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
13085  break;
13086  case ArgType::NoMatch:
13087  Diag = diag::warn_format_conversion_argument_type_mismatch;
13088  break;
13089  }
13090 
13091  // In this case, the specifier is wrong and should be changed to match
13092  // the argument.
13093  EmitFormatDiagnostic(S.PDiag(Diag)
13094  << AT.getRepresentativeTypeName(S.Context)
13095  << IntendedTy << IsEnum << E->getSourceRange(),
13096  E->getBeginLoc(),
13097  /*IsStringLocation*/ false, SpecRange,
13098  FixItHint::CreateReplacement(SpecRange, os.str()));
13099  } else {
13100  // The canonical type for formatting this value is different from the
13101  // actual type of the expression. (This occurs, for example, with Darwin's
13102  // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
13103  // should be printed as 'long' for 64-bit compatibility.)
13104  // Rather than emitting a normal format/argument mismatch, we want to
13105  // add a cast to the recommended type (and correct the format string
13106  // if necessary). We should also do so for scoped enumerations.
13107  SmallString<16> CastBuf;
13108  llvm::raw_svector_ostream CastFix(CastBuf);
13109  CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
13110  IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
13111  CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
13112 
13114  ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
13115  IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
13116  E->getExprLoc());
13117  if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
13118  Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
13119 
13120  if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
13121  // If there's already a cast present, just replace it.
13122  SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
13123  Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
13124 
13125  } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
13126  // If the expression has high enough precedence,
13127  // just write the C-style cast.
13128  Hints.push_back(
13129  FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
13130  } else {
13131  // Otherwise, add parens around the expression as well as the cast.
13132  CastFix << "(";
13133  Hints.push_back(
13134  FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
13135 
13136  // We don't use getLocForEndOfToken because it returns invalid source
13137  // locations for macro expansions (by design).
13141  Hints.push_back(FixItHint::CreateInsertion(After, ")"));
13142  }
13143 
13144  if (ShouldNotPrintDirectly && !IsScopedEnum) {
13145  // The expression has a type that should not be printed directly.
13146  // We extract the name from the typedef because we don't want to show
13147  // the underlying type in the diagnostic.
13148  StringRef Name;
13149  if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
13150  Name = TypedefTy->getDecl()->getName();
13151  else
13152  Name = CastTyName;
13153  unsigned Diag = Match == ArgType::NoMatchPedantic
13154  ? diag::warn_format_argument_needs_cast_pedantic
13155  : diag::warn_format_argument_needs_cast;
13156  EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
13157  << E->getSourceRange(),
13158  E->getBeginLoc(), /*IsStringLocation=*/false,
13159  SpecRange, Hints);
13160  } else {
13161  // In this case, the expression could be printed using a different
13162  // specifier, but we've decided that the specifier is probably correct
13163  // and we should cast instead. Just use the normal warning message.
13164 
13165  unsigned Diag =
13166  IsScopedEnum
13167  ? diag::warn_format_conversion_argument_type_mismatch_pedantic
13168  : diag::warn_format_conversion_argument_type_mismatch;
13169 
13170  EmitFormatDiagnostic(
13171  S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
13172  << IsEnum << E->getSourceRange(),
13173  E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
13174  }
13175  }
13176  } else {
13177  const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
13178  SpecifierLen);
13179  // Since the warning for passing non-POD types to variadic functions
13180  // was deferred until now, we emit a warning for non-POD
13181  // arguments here.
13182  bool EmitTypeMismatch = false;
13183  switch (S.isValidVarArgType(ExprTy)) {
13184  case Sema::VAK_Valid:
13185  case Sema::VAK_ValidInCXX11: {
13186  unsigned Diag;
13187  switch (Match) {
13188  case ArgType::Match:
13189  case ArgType::MatchPromotion:
13190  case ArgType::NoMatchPromotionTypeConfusion:
13191  case ArgType::NoMatchSignedness:
13192  llvm_unreachable("expected non-matching");
13193  case ArgType::NoMatchPedantic:
13194  Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
13195  break;
13196  case ArgType::NoMatchTypeConfusion:
13197  Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
13198  break;
13199  case ArgType::NoMatch:
13200  Diag = diag::warn_format_conversion_argument_type_mismatch;
13201  break;
13202  }
13203 
13204  EmitFormatDiagnostic(
13205  S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
13206  << IsEnum << CSR << E->getSourceRange(),
13207  E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
13208  break;
13209  }
13210  case Sema::VAK_Undefined:
13212  if (CallType == Sema::VariadicDoesNotApply) {
13213  EmitTypeMismatch = true;
13214  } else {
13215  EmitFormatDiagnostic(
13216  S.PDiag(diag::warn_non_pod_vararg_with_format_string)
13217  << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
13218  << AT.getRepresentativeTypeName(S.Context) << CSR
13219  << E->getSourceRange(),
13220  E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
13221  checkForCStrMembers(AT, E);
13222  }
13223  break;
13224 
13225  case Sema::VAK_Invalid:
13226  if (CallType == Sema::VariadicDoesNotApply)
13227  EmitTypeMismatch = true;
13228  else if (ExprTy->isObjCObjectType())
13229  EmitFormatDiagnostic(
13230  S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
13231  << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
13232  << AT.getRepresentativeTypeName(S.Context) << CSR
13233  << E->getSourceRange(),
13234  E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
13235  else
13236  // FIXME: If this is an initializer list, suggest removing the braces
13237  // or inserting a cast to the target type.
13238  S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
13239  << isa<InitListExpr>(E) << ExprTy << CallType
13240  << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
13241  break;
13242  }
13243 
13244  if (EmitTypeMismatch) {
13245  // The function is not variadic, so we do not generate warnings about
13246  // being allowed to pass that object as a variadic argument. Instead,
13247  // since there are inherently no printf specifiers for types which cannot
13248  // be passed as variadic arguments, emit a plain old specifier mismatch
13249  // argument.
13250  EmitFormatDiagnostic(
13251  S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
13252  << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
13253  << E->getSourceRange(),
13254  E->getBeginLoc(), false, CSR);
13255  }
13256 
13257  assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
13258  "format string specifier index out of range");
13259  CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
13260  }
13261 
13262  return true;
13263 }
13264 
13265 //===--- CHECK: Scanf format string checking ------------------------------===//
13266 
13267 namespace {
13268 
13269 class CheckScanfHandler : public CheckFormatHandler {
13270 public:
13271  CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
13272  const Expr *origFormatExpr, Sema::FormatStringType type,
13273  unsigned firstDataArg, unsigned numDataArgs,
13274  const char *beg, Sema::FormatArgumentPassingKind APK,
13275  ArrayRef<const Expr *> Args, unsigned formatIdx,
13276  bool inFunctionCall, Sema::VariadicCallType CallType,
13277  llvm::SmallBitVector &CheckedVarArgs,
13278  UncoveredArgHandler &UncoveredArg)
13279  : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
13280  numDataArgs, beg, APK, Args, formatIdx,
13281  inFunctionCall, CallType, CheckedVarArgs,
13282  UncoveredArg) {}
13283 
13284  bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
13285  const char *startSpecifier,
13286  unsigned specifierLen) override;
13287 
13288  bool HandleInvalidScanfConversionSpecifier(
13290  const char *startSpecifier,
13291  unsigned specifierLen) override;
13292 
13293  void HandleIncompleteScanList(const char *start, const char *end) override;
13294 };
13295 
13296 } // namespace
13297 
13298 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
13299  const char *end) {
13300  EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
13301  getLocationOfByte(end), /*IsStringLocation*/true,
13302  getSpecifierRange(start, end - start));
13303 }
13304 
13305 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
13307  const char *startSpecifier,
13308  unsigned specifierLen) {
13310  FS.getConversionSpecifier();
13311 
13312  return HandleInvalidConversionSpecifier(FS.getArgIndex(),
13313  getLocationOfByte(CS.getStart()),
13314  startSpecifier, specifierLen,
13315  CS.getStart(), CS.getLength());
13316 }
13317 
13318 bool CheckScanfHandler::HandleScanfSpecifier(
13320  const char *startSpecifier,
13321  unsigned specifierLen) {
13322  using namespace analyze_scanf;
13323  using namespace analyze_format_string;
13324 
13325  const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
13326 
13327  // Handle case where '%' and '*' don't consume an argument. These shouldn't
13328  // be used to decide if we are using positional arguments consistently.
13329  if (FS.consumesDataArgument()) {
13330  if (atFirstArg) {
13331  atFirstArg = false;
13332  usesPositionalArgs = FS.usesPositionalArg();
13333  }
13334  else if (usesPositionalArgs != FS.usesPositionalArg()) {
13335  HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
13336  startSpecifier, specifierLen);
13337  return false;
13338  }
13339  }
13340 
13341  // Check if the field with is non-zero.
13342  const OptionalAmount &Amt = FS.getFieldWidth();
13343  if (Amt.getHowSpecified() == OptionalAmount::Constant) {
13344  if (Amt.getConstantAmount() == 0) {
13345  const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
13346  Amt.getConstantLength());
13347  EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
13348  getLocationOfByte(Amt.getStart()),
13349  /*IsStringLocation*/true, R,
13351  }
13352  }
13353 
13354  if (!FS.consumesDataArgument()) {
13355  // FIXME: Technically specifying a precision or field width here
13356  // makes no sense. Worth issuing a warning at some point.
13357  return true;
13358  }
13359 
13360  // Consume the argument.
13361  unsigned argIndex = FS.getArgIndex();
13362  if (argIndex < NumDataArgs) {
13363  // The check to see if the argIndex is valid will come later.
13364  // We set the bit here because we may exit early from this
13365  // function if we encounter some other error.
13366  CoveredArgs.set(argIndex);
13367  }
13368 
13369  // Check the length modifier is valid with the given conversion specifier.
13370  if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
13371  S.getLangOpts()))
13372  HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
13373  diag::warn_format_nonsensical_length);
13374  else if (!FS.hasStandardLengthModifier())
13375  HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
13376  else if (!FS.hasStandardLengthConversionCombination())
13377  HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
13378  diag::warn_format_non_standard_conversion_spec);
13379 
13380  if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
13381  HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
13382 
13383  // The remaining checks depend on the data arguments.
13384  if (ArgPassingKind == Sema::FAPK_VAList)
13385  return true;
13386 
13387  if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
13388  return false;
13389 
13390  // Check that the argument type matches the format specifier.
13391  const Expr *Ex = getDataArg(argIndex);
13392  if (!Ex)
13393  return true;
13394 
13395  const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
13396 
13397  if (!AT.isValid()) {
13398  return true;
13399  }
13400 
13402  AT.matchesType(S.Context, Ex->getType());
13403  Match = handleFormatSignedness(Match, S.getDiagnostics(), Ex->getExprLoc());
13406  return true;
13407 
13408  ScanfSpecifier fixedFS = FS;
13409  bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
13410  S.getLangOpts(), S.Context);
13411 
13412  unsigned Diag =
13413  Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
13414  : diag::warn_format_conversion_argument_type_mismatch;
13415 
13416  if (Success) {
13417  // Get the fix string from the fixed format specifier.
13418  SmallString<128> buf;
13419  llvm::raw_svector_ostream os(buf);
13420  fixedFS.toString(os);
13421 
13422  EmitFormatDiagnostic(
13424  << Ex->getType() << false << Ex->getSourceRange(),
13425  Ex->getBeginLoc(),
13426  /*IsStringLocation*/ false,
13427  getSpecifierRange(startSpecifier, specifierLen),
13429  getSpecifierRange(startSpecifier, specifierLen), os.str()));
13430  } else {
13431  EmitFormatDiagnostic(S.PDiag(Diag)
13433  << Ex->getType() << false << Ex->getSourceRange(),
13434  Ex->getBeginLoc(),
13435  /*IsStringLocation*/ false,
13436  getSpecifierRange(startSpecifier, specifierLen));
13437  }
13438 
13439  return true;
13440 }
13441 
13442 static void CheckFormatString(
13443  Sema &S, const FormatStringLiteral *FExpr, const Expr *OrigFormatExpr,
13445  unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type,
13446  bool inFunctionCall, Sema::VariadicCallType CallType,
13447  llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
13448  bool IgnoreStringsWithoutSpecifiers) {
13449  // CHECK: is the format string a wide literal?
13450  if (!FExpr->isAscii() && !FExpr->isUTF8()) {
13451  CheckFormatHandler::EmitFormatDiagnostic(
13452  S, inFunctionCall, Args[format_idx],
13453  S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
13454  /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
13455  return;
13456  }
13457 
13458  // Str - The format string. NOTE: this is NOT null-terminated!
13459  StringRef StrRef = FExpr->getString();
13460  const char *Str = StrRef.data();
13461  // Account for cases where the string literal is truncated in a declaration.
13462  const ConstantArrayType *T =
13463  S.Context.getAsConstantArrayType(FExpr->getType());
13464  assert(T && "String literal not of constant array type!");
13465  size_t TypeSize = T->getZExtSize();
13466  size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
13467  const unsigned numDataArgs = Args.size() - firstDataArg;
13468 
13469  if (IgnoreStringsWithoutSpecifiers &&
13471  Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
13472  return;
13473 
13474  // Emit a warning if the string literal is truncated and does not contain an
13475  // embedded null character.
13476  if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
13477  CheckFormatHandler::EmitFormatDiagnostic(
13478  S, inFunctionCall, Args[format_idx],
13479  S.PDiag(diag::warn_printf_format_string_not_null_terminated),
13480  FExpr->getBeginLoc(),
13481  /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
13482  return;
13483  }
13484 
13485  // CHECK: empty format string?
13486  if (StrLen == 0 && numDataArgs > 0) {
13487  CheckFormatHandler::EmitFormatDiagnostic(
13488  S, inFunctionCall, Args[format_idx],
13489  S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
13490  /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
13491  return;
13492  }
13493 
13496  Type == Sema::FST_OSTrace) {
13497  CheckPrintfHandler H(
13498  S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
13499  (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, APK,
13500  Args, format_idx, inFunctionCall, CallType, CheckedVarArgs,
13501  UncoveredArg);
13502 
13504  H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
13506  H.DoneProcessing();
13507  } else if (Type == Sema::FST_Scanf) {
13508  CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
13509  numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
13510  CallType, CheckedVarArgs, UncoveredArg);
13511 
13513  H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
13514  H.DoneProcessing();
13515  } // TODO: handle other formats
13516 }
13517 
13519  // Str - The format string. NOTE: this is NOT null-terminated!
13520  StringRef StrRef = FExpr->getString();
13521  const char *Str = StrRef.data();
13522  // Account for cases where the string literal is truncated in a declaration.
13523  const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
13524  assert(T && "String literal not of constant array type!");
13525  size_t TypeSize = T->getZExtSize();
13526  size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
13527  return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
13528  getLangOpts(),
13529  Context.getTargetInfo());
13530 }
13531 
13532 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
13533 
13534 // Returns the related absolute value function that is larger, of 0 if one
13535 // does not exist.
13536 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
13537  switch (AbsFunction) {
13538  default:
13539  return 0;
13540 
13541  case Builtin::BI__builtin_abs:
13542  return Builtin::BI__builtin_labs;
13543  case Builtin::BI__builtin_labs:
13544  return Builtin::BI__builtin_llabs;
13545  case Builtin::BI__builtin_llabs:
13546  return 0;
13547 
13548  case Builtin::BI__builtin_fabsf:
13549  return Builtin::BI__builtin_fabs;
13550  case Builtin::BI__builtin_fabs:
13551  return Builtin::BI__builtin_fabsl;
13552  case Builtin::BI__builtin_fabsl:
13553  return 0;
13554 
13555  case Builtin::BI__builtin_cabsf:
13556  return Builtin::BI__builtin_cabs;
13557  case Builtin::BI__builtin_cabs:
13558  return Builtin::BI__builtin_cabsl;
13559  case Builtin::BI__builtin_cabsl:
13560  return 0;
13561 
13562  case Builtin::BIabs:
13563  return Builtin::BIlabs;
13564  case Builtin::BIlabs:
13565  return Builtin::BIllabs;
13566  case Builtin::BIllabs:
13567  return 0;
13568 
13569  case Builtin::BIfabsf:
13570  return Builtin::BIfabs;
13571  case Builtin::BIfabs:
13572  return Builtin::BIfabsl;
13573  case Builtin::BIfabsl:
13574  return 0;
13575 
13576  case Builtin::BIcabsf:
13577  return Builtin::BIcabs;
13578  case Builtin::BIcabs:
13579  return Builtin::BIcabsl;
13580  case Builtin::BIcabsl:
13581  return 0;
13582  }
13583 }
13584 
13585 // Returns the argument type of the absolute value function.
13587  unsigned AbsType) {
13588  if (AbsType == 0)
13589  return QualType();
13590 
13592  QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
13593  if (Error != ASTContext::GE_None)
13594  return QualType();
13595 
13597  if (!FT)
13598  return QualType();
13599 
13600  if (FT->getNumParams() != 1)
13601  return QualType();
13602 
13603  return FT->getParamType(0);
13604 }
13605 
13606 // Returns the best absolute value function, or zero, based on type and
13607 // current absolute value function.
13608 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
13609  unsigned AbsFunctionKind) {
13610  unsigned BestKind = 0;
13611  uint64_t ArgSize = Context.getTypeSize(ArgType);
13612  for (unsigned Kind = AbsFunctionKind; Kind != 0;
13614  QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
13615  if (Context.getTypeSize(ParamType) >= ArgSize) {
13616  if (BestKind == 0)
13617  BestKind = Kind;
13618  else if (Context.hasSameType(ParamType, ArgType)) {
13619  BestKind = Kind;
13620  break;
13621  }
13622  }
13623  }
13624  return BestKind;
13625 }
13626 
13630  AVK_Complex
13631 };
13632 
13635  return AVK_Integer;
13636  if (T->isRealFloatingType())
13637  return AVK_Floating;
13638  if (T->isAnyComplexType())
13639  return AVK_Complex;
13640 
13641  llvm_unreachable("Type not integer, floating, or complex");
13642 }
13643 
13644 // Changes the absolute value function to a different type. Preserves whether
13645 // the function is a builtin.
13646 static unsigned changeAbsFunction(unsigned AbsKind,
13647  AbsoluteValueKind ValueKind) {
13648  switch (ValueKind) {
13649  case AVK_Integer:
13650  switch (AbsKind) {
13651  default:
13652  return 0;
13653  case Builtin::BI__builtin_fabsf:
13654  case Builtin::BI__builtin_fabs:
13655  case Builtin::BI__builtin_fabsl:
13656  case Builtin::BI__builtin_cabsf:
13657  case Builtin::BI__builtin_cabs:
13658  case Builtin::BI__builtin_cabsl:
13659  return Builtin::BI__builtin_abs;
13660  case Builtin::BIfabsf:
13661  case Builtin::BIfabs:
13662  case Builtin::BIfabsl:
13663  case Builtin::BIcabsf:
13664  case Builtin::BIcabs:
13665  case Builtin::BIcabsl:
13666  return Builtin::BIabs;
13667  }
13668  case AVK_Floating:
13669  switch (AbsKind) {
13670  default:
13671  return 0;
13672  case Builtin::BI__builtin_abs:
13673  case Builtin::BI__builtin_labs:
13674  case Builtin::BI__builtin_llabs:
13675  case Builtin::BI__builtin_cabsf:
13676  case Builtin::BI__builtin_cabs:
13677  case Builtin::BI__builtin_cabsl:
13678  return Builtin::BI__builtin_fabsf;
13679  case Builtin::BIabs:
13680  case Builtin::BIlabs:
13681  case Builtin::BIllabs:
13682  case Builtin::BIcabsf:
13683  case Builtin::BIcabs:
13684  case Builtin::BIcabsl:
13685  return Builtin::BIfabsf;
13686  }
13687  case AVK_Complex:
13688  switch (AbsKind) {
13689  default:
13690  return 0;
13691  case Builtin::BI__builtin_abs:
13692  case Builtin::BI__builtin_labs:
13693  case Builtin::BI__builtin_llabs:
13694  case Builtin::BI__builtin_fabsf:
13695  case Builtin::BI__builtin_fabs:
13696  case Builtin::BI__builtin_fabsl:
13697  return Builtin::BI__builtin_cabsf;
13698  case Builtin::BIabs:
13699  case Builtin::BIlabs:
13700  case Builtin::BIllabs:
13701  case Builtin::BIfabsf:
13702  case Builtin::BIfabs:
13703  case Builtin::BIfabsl:
13704  return Builtin::BIcabsf;
13705  }
13706  }
13707  llvm_unreachable("Unable to convert function");
13708 }
13709 
13710 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
13711  const IdentifierInfo *FnInfo = FDecl->getIdentifier();
13712  if (!FnInfo)
13713  return 0;
13714 
13715  switch (FDecl->getBuiltinID()) {
13716  default:
13717  return 0;
13718  case Builtin::BI__builtin_abs:
13719  case Builtin::BI__builtin_fabs:
13720  case Builtin::BI__builtin_fabsf:
13721  case Builtin::BI__builtin_fabsl:
13722  case Builtin::BI__builtin_labs:
13723  case Builtin::BI__builtin_llabs:
13724  case Builtin::BI__builtin_cabs:
13725  case Builtin::BI__builtin_cabsf:
13726  case Builtin::BI__builtin_cabsl:
13727  case Builtin::BIabs:
13728  case Builtin::BIlabs:
13729  case Builtin::BIllabs:
13730  case Builtin::BIfabs:
13731  case Builtin::BIfabsf:
13732  case Builtin::BIfabsl:
13733  case Builtin::BIcabs:
13734  case Builtin::BIcabsf:
13735  case Builtin::BIcabsl:
13736  return FDecl->getBuiltinID();
13737  }
13738  llvm_unreachable("Unknown Builtin type");
13739 }
13740 
13741 // If the replacement is valid, emit a note with replacement function.
13742 // Additionally, suggest including the proper header if not already included.
13743 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
13744  unsigned AbsKind, QualType ArgType) {
13745  bool EmitHeaderHint = true;
13746  const char *HeaderName = nullptr;
13747  StringRef FunctionName;
13748  if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
13749  FunctionName = "std::abs";
13750  if (ArgType->isIntegralOrEnumerationType()) {
13751  HeaderName = "cstdlib";
13752  } else if (ArgType->isRealFloatingType()) {
13753  HeaderName = "cmath";
13754  } else {
13755  llvm_unreachable("Invalid Type");
13756  }
13757 
13758  // Lookup all std::abs
13759  if (NamespaceDecl *Std = S.getStdNamespace()) {
13760  LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
13761  R.suppressDiagnostics();
13762  S.LookupQualifiedName(R, Std);
13763 
13764  for (const auto *I : R) {
13765  const FunctionDecl *FDecl = nullptr;
13766  if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
13767  FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
13768  } else {
13769  FDecl = dyn_cast<FunctionDecl>(I);
13770  }
13771  if (!FDecl)
13772  continue;
13773 
13774  // Found std::abs(), check that they are the right ones.
13775  if (FDecl->getNumParams() != 1)
13776  continue;
13777 
13778  // Check that the parameter type can handle the argument.
13779  QualType ParamType = FDecl->getParamDecl(0)->getType();
13780  if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
13781  S.Context.getTypeSize(ArgType) <=
13782  S.Context.getTypeSize(ParamType)) {
13783  // Found a function, don't need the header hint.
13784  EmitHeaderHint = false;
13785  break;
13786  }
13787  }
13788  }
13789  } else {
13790  FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
13791  HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
13792 
13793  if (HeaderName) {
13794  DeclarationName DN(&S.Context.Idents.get(FunctionName));
13795  LookupResult R(S, DN, Loc, Sema::LookupAnyName);
13796  R.suppressDiagnostics();
13797  S.LookupName(R, S.getCurScope());
13798 
13799  if (R.isSingleResult()) {
13800  FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
13801  if (FD && FD->getBuiltinID() == AbsKind) {
13802  EmitHeaderHint = false;
13803  } else {
13804  return;
13805  }
13806  } else if (!R.empty()) {
13807  return;
13808  }
13809  }
13810  }
13811 
13812  S.Diag(Loc, diag::note_replace_abs_function)
13813  << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
13814 
13815  if (!HeaderName)
13816  return;
13817 
13818  if (!EmitHeaderHint)
13819  return;
13820 
13821  S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
13822  << FunctionName;
13823 }
13824 
13825 template <std::size_t StrLen>
13826 static bool IsStdFunction(const FunctionDecl *FDecl,
13827  const char (&Str)[StrLen]) {
13828  if (!FDecl)
13829  return false;
13830  if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
13831  return false;
13832  if (!FDecl->isInStdNamespace())
13833  return false;
13834 
13835  return true;
13836 }
13837 
13838 void Sema::CheckInfNaNFunction(const CallExpr *Call,
13839  const FunctionDecl *FDecl) {
13840  FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
13841  if ((IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered") ||
13842  (Call->getBuiltinCallee() == Builtin::BI__builtin_nanf)) &&
13843  FPO.getNoHonorNaNs())
13844  Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
13845  << 1 << 0 << Call->getSourceRange();
13846  else if ((IsStdFunction(FDecl, "isinf") ||
13847  (IsStdFunction(FDecl, "isfinite") ||
13848  (FDecl->getIdentifier() && FDecl->getName() == "infinity"))) &&
13849  FPO.getNoHonorInfs())
13850  Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
13851  << 0 << 0 << Call->getSourceRange();
13852 }
13853 
13854 // Warn when using the wrong abs() function.
13855 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
13856  const FunctionDecl *FDecl) {
13857  if (Call->getNumArgs() != 1)
13858  return;
13859 
13860  unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
13861  bool IsStdAbs = IsStdFunction(FDecl, "abs");
13862  if (AbsKind == 0 && !IsStdAbs)
13863  return;
13864 
13865  QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
13866  QualType ParamType = Call->getArg(0)->getType();
13867 
13868  // Unsigned types cannot be negative. Suggest removing the absolute value
13869  // function call.
13870  if (ArgType->isUnsignedIntegerType()) {
13871  StringRef FunctionName =
13872  IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
13873  Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
13874  Diag(Call->getExprLoc(), diag::note_remove_abs)
13875  << FunctionName
13876  << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
13877  return;
13878  }
13879 
13880  // Taking the absolute value of a pointer is very suspicious, they probably
13881  // wanted to index into an array, dereference a pointer, call a function, etc.
13882  if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
13883  unsigned DiagType = 0;
13884  if (ArgType->isFunctionType())
13885  DiagType = 1;
13886  else if (ArgType->isArrayType())
13887  DiagType = 2;
13888 
13889  Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
13890  return;
13891  }
13892 
13893  // std::abs has overloads which prevent most of the absolute value problems
13894  // from occurring.
13895  if (IsStdAbs)
13896  return;
13897 
13898  AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
13899  AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
13900 
13901  // The argument and parameter are the same kind. Check if they are the right
13902  // size.
13903  if (ArgValueKind == ParamValueKind) {
13904  if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
13905  return;
13906 
13907  unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
13908  Diag(Call->getExprLoc(), diag::warn_abs_too_small)
13909  << FDecl << ArgType << ParamType;
13910 
13911  if (NewAbsKind == 0)
13912  return;
13913 
13914  emitReplacement(*this, Call->getExprLoc(),
13915  Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
13916  return;
13917  }
13918 
13919  // ArgValueKind != ParamValueKind
13920  // The wrong type of absolute value function was used. Attempt to find the
13921  // proper one.
13922  unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
13923  NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
13924  if (NewAbsKind == 0)
13925  return;
13926 
13927  Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
13928  << FDecl << ParamValueKind << ArgValueKind;
13929 
13930  emitReplacement(*this, Call->getExprLoc(),
13931  Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
13932 }
13933 
13934 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
13935 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
13936  const FunctionDecl *FDecl) {
13937  if (!Call || !FDecl) return;
13938 
13939  // Ignore template specializations and macros.
13940  if (inTemplateInstantiation()) return;
13941  if (Call->getExprLoc().isMacroID()) return;
13942 
13943  // Only care about the one template argument, two function parameter std::max
13944  if (Call->getNumArgs() != 2) return;
13945  if (!IsStdFunction(FDecl, "max")) return;
13946  const auto * ArgList = FDecl->getTemplateSpecializationArgs();
13947  if (!ArgList) return;
13948  if (ArgList->size() != 1) return;
13949 
13950  // Check that template type argument is unsigned integer.
13951  const auto& TA = ArgList->get(0);
13952  if (TA.getKind() != TemplateArgument::Type) return;
13953  QualType ArgType = TA.getAsType();
13954  if (!ArgType->isUnsignedIntegerType()) return;
13955 
13956  // See if either argument is a literal zero.
13957  auto IsLiteralZeroArg = [](const Expr* E) -> bool {
13958  const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
13959  if (!MTE) return false;
13960  const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
13961  if (!Num) return false;
13962  if (Num->getValue() != 0) return false;
13963  return true;
13964  };
13965 
13966  const Expr *FirstArg = Call->getArg(0);
13967  const Expr *SecondArg = Call->getArg(1);
13968  const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
13969  const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
13970 
13971  // Only warn when exactly one argument is zero.
13972  if (IsFirstArgZero == IsSecondArgZero) return;
13973 
13974  SourceRange FirstRange = FirstArg->getSourceRange();
13975  SourceRange SecondRange = SecondArg->getSourceRange();
13976 
13977  SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
13978 
13979  Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
13980  << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
13981 
13982  // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
13983  SourceRange RemovalRange;
13984  if (IsFirstArgZero) {
13985  RemovalRange = SourceRange(FirstRange.getBegin(),
13986  SecondRange.getBegin().getLocWithOffset(-1));
13987  } else {
13988  RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
13989  SecondRange.getEnd());
13990  }
13991 
13992  Diag(Call->getExprLoc(), diag::note_remove_max_call)
13993  << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
13994  << FixItHint::CreateRemoval(RemovalRange);
13995 }
13996 
13997 //===--- CHECK: Standard memory functions ---------------------------------===//
13998 
13999 /// Takes the expression passed to the size_t parameter of functions
14000 /// such as memcmp, strncat, etc and warns if it's a comparison.
14001 ///
14002 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
14003 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
14004  IdentifierInfo *FnName,
14005  SourceLocation FnLoc,
14006  SourceLocation RParenLoc) {
14007  const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
14008  if (!Size)
14009  return false;
14010 
14011  // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
14012  if (!Size->isComparisonOp() && !Size->isLogicalOp())
14013  return false;
14014 
14015  SourceRange SizeRange = Size->getSourceRange();
14016  S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
14017  << SizeRange << FnName;
14018  S.Diag(FnLoc, diag::note_memsize_comparison_paren)
14019  << FnName
14021  S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
14022  << FixItHint::CreateRemoval(RParenLoc);
14023  S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
14024  << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
14026  ")");
14027 
14028  return true;
14029 }
14030 
14031 /// Determine whether the given type is or contains a dynamic class type
14032 /// (e.g., whether it has a vtable).
14034  bool &IsContained) {
14035  // Look through array types while ignoring qualifiers.
14036  const Type *Ty = T->getBaseElementTypeUnsafe();
14037  IsContained = false;
14038 
14039  const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
14040  RD = RD ? RD->getDefinition() : nullptr;
14041  if (!RD || RD->isInvalidDecl())
14042  return nullptr;
14043 
14044  if (RD->isDynamicClass())
14045  return RD;
14046 
14047  // Check all the fields. If any bases were dynamic, the class is dynamic.
14048  // It's impossible for a class to transitively contain itself by value, so
14049  // infinite recursion is impossible.
14050  for (auto *FD : RD->fields()) {
14051  bool SubContained;
14052  if (const CXXRecordDecl *ContainedRD =
14053  getContainedDynamicClass(FD->getType(), SubContained)) {
14054  IsContained = true;
14055  return ContainedRD;
14056  }
14057  }
14058 
14059  return nullptr;
14060 }
14061 
14063  if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
14064  if (Unary->getKind() == UETT_SizeOf)
14065  return Unary;
14066  return nullptr;
14067 }
14068 
14069 /// If E is a sizeof expression, returns its argument expression,
14070 /// otherwise returns NULL.
14071 static const Expr *getSizeOfExprArg(const Expr *E) {
14073  if (!SizeOf->isArgumentType())
14074  return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
14075  return nullptr;
14076 }
14077 
14078 /// If E is a sizeof expression, returns its argument type.
14079 static QualType getSizeOfArgType(const Expr *E) {
14081  return SizeOf->getTypeOfArgument();
14082  return QualType();
14083 }
14084 
14085 namespace {
14086 
14087 struct SearchNonTrivialToInitializeField
14088  : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
14089  using Super =
14091 
14092  SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
14093 
14094  void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
14095  SourceLocation SL) {
14096  if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
14097  asDerived().visitArray(PDIK, AT, SL);
14098  return;
14099  }
14100 
14101  Super::visitWithKind(PDIK, FT, SL);
14102  }
14103 
14104  void visitARCStrong(QualType FT, SourceLocation SL) {
14105  S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
14106  }
14107  void visitARCWeak(QualType FT, SourceLocation SL) {
14108  S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
14109  }
14110  void visitStruct(QualType FT, SourceLocation SL) {
14111  for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
14112  visit(FD->getType(), FD->getLocation());
14113  }
14114  void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
14115  const ArrayType *AT, SourceLocation SL) {
14116  visit(getContext().getBaseElementType(AT), SL);
14117  }
14118  void visitTrivial(QualType FT, SourceLocation SL) {}
14119 
14120  static void diag(QualType RT, const Expr *E, Sema &S) {
14121  SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
14122  }
14123 
14124  ASTContext &getContext() { return S.getASTContext(); }
14125 
14126  const Expr *E;
14127  Sema &S;
14128 };
14129 
14130 struct SearchNonTrivialToCopyField
14131  : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
14133 
14134  SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
14135 
14136  void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
14137  SourceLocation SL) {
14138  if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
14139  asDerived().visitArray(PCK, AT, SL);
14140  return;
14141  }
14142 
14143  Super::visitWithKind(PCK, FT, SL);
14144  }
14145 
14146  void visitARCStrong(QualType FT, SourceLocation SL) {
14147  S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
14148  }
14149  void visitARCWeak(QualType FT, SourceLocation SL) {
14150  S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
14151  }
14152  void visitStruct(QualType FT, SourceLocation SL) {
14153  for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
14154  visit(FD->getType(), FD->getLocation());
14155  }
14156  void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
14157  SourceLocation SL) {
14158  visit(getContext().getBaseElementType(AT), SL);
14159  }
14160  void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
14161  SourceLocation SL) {}
14162  void visitTrivial(QualType FT, SourceLocation SL) {}
14163  void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
14164 
14165  static void diag(QualType RT, const Expr *E, Sema &S) {
14166  SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
14167  }
14168 
14169  ASTContext &getContext() { return S.getASTContext(); }
14170 
14171  const Expr *E;
14172  Sema &S;
14173 };
14174 
14175 }
14176 
14177 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
14178 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
14179  SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
14180 
14181  if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
14182  if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
14183  return false;
14184 
14185  return doesExprLikelyComputeSize(BO->getLHS()) ||
14186  doesExprLikelyComputeSize(BO->getRHS());
14187  }
14188 
14189  return getAsSizeOfExpr(SizeofExpr) != nullptr;
14190 }
14191 
14192 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
14193 ///
14194 /// \code
14195 /// #define MACRO 0
14196 /// foo(MACRO);
14197 /// foo(0);
14198 /// \endcode
14199 ///
14200 /// This should return true for the first call to foo, but not for the second
14201 /// (regardless of whether foo is a macro or function).
14203  SourceLocation CallLoc,
14204  SourceLocation ArgLoc) {
14205  if (!CallLoc.isMacroID())
14206  return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
14207 
14208  return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
14209  SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
14210 }
14211 
14212 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
14213 /// last two arguments transposed.
14214 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
14215  if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
14216  return;
14217 
14218  const Expr *SizeArg =
14219  Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
14220 
14221  auto isLiteralZero = [](const Expr *E) {
14222  return (isa<IntegerLiteral>(E) &&
14223  cast<IntegerLiteral>(E)->getValue() == 0) ||
14224  (isa<CharacterLiteral>(E) &&
14225  cast<CharacterLiteral>(E)->getValue() == 0);
14226  };
14227 
14228  // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
14229  SourceLocation CallLoc = Call->getRParenLoc();
14231  if (isLiteralZero(SizeArg) &&
14232  !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
14233 
14234  SourceLocation DiagLoc = SizeArg->getExprLoc();
14235 
14236  // Some platforms #define bzero to __builtin_memset. See if this is the
14237  // case, and if so, emit a better diagnostic.
14238  if (BId == Builtin::BIbzero ||
14240  CallLoc, SM, S.getLangOpts()) == "bzero")) {
14241  S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
14242  S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
14243  } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
14244  S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
14245  S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
14246  }
14247  return;
14248  }
14249 
14250  // If the second argument to a memset is a sizeof expression and the third
14251  // isn't, this is also likely an error. This should catch
14252  // 'memset(buf, sizeof(buf), 0xff)'.
14253  if (BId == Builtin::BImemset &&
14254  doesExprLikelyComputeSize(Call->getArg(1)) &&
14255  !doesExprLikelyComputeSize(Call->getArg(2))) {
14256  SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
14257  S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
14258  S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
14259  return;
14260  }
14261 }
14262 
14263 /// Check for dangerous or invalid arguments to memset().
14264 ///
14265 /// This issues warnings on known problematic, dangerous or unspecified
14266 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
14267 /// function calls.
14268 ///
14269 /// \param Call The call expression to diagnose.
14270 void Sema::CheckMemaccessArguments(const CallExpr *Call,
14271  unsigned BId,
14272  IdentifierInfo *FnName) {
14273  assert(BId != 0);
14274 
14275  // It is possible to have a non-standard definition of memset. Validate
14276  // we have enough arguments, and if not, abort further checking.
14277  unsigned ExpectedNumArgs =
14278  (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
14279  if (Call->getNumArgs() < ExpectedNumArgs)
14280  return;
14281 
14282  unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
14283  BId == Builtin::BIstrndup ? 1 : 2);
14284  unsigned LenArg =
14285  (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
14286  const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
14287 
14288  if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
14289  Call->getBeginLoc(), Call->getRParenLoc()))
14290  return;
14291 
14292  // Catch cases like 'memset(buf, sizeof(buf), 0)'.
14293  CheckMemaccessSize(*this, BId, Call);
14294 
14295  // We have special checking when the length is a sizeof expression.
14296  QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
14297  const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
14298  llvm::FoldingSetNodeID SizeOfArgID;
14299 
14300  // Although widely used, 'bzero' is not a standard function. Be more strict
14301  // with the argument types before allowing diagnostics and only allow the
14302  // form bzero(ptr, sizeof(...)).
14303  QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
14304  if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
14305  return;
14306 
14307  for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
14308  const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
14309  SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
14310 
14311  QualType DestTy = Dest->getType();
14312  QualType PointeeTy;
14313  if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
14314  PointeeTy = DestPtrTy->getPointeeType();
14315 
14316  // Never warn about void type pointers. This can be used to suppress
14317  // false positives.
14318  if (PointeeTy->isVoidType())
14319  continue;
14320 
14321  // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
14322  // actually comparing the expressions for equality. Because computing the
14323  // expression IDs can be expensive, we only do this if the diagnostic is
14324  // enabled.
14325  if (SizeOfArg &&
14326  !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
14327  SizeOfArg->getExprLoc())) {
14328  // We only compute IDs for expressions if the warning is enabled, and
14329  // cache the sizeof arg's ID.
14330  if (SizeOfArgID == llvm::FoldingSetNodeID())
14331  SizeOfArg->Profile(SizeOfArgID, Context, true);
14332  llvm::FoldingSetNodeID DestID;
14333  Dest->Profile(DestID, Context, true);
14334  if (DestID == SizeOfArgID) {
14335  // TODO: For strncpy() and friends, this could suggest sizeof(dst)
14336  // over sizeof(src) as well.
14337  unsigned ActionIdx = 0; // Default is to suggest dereferencing.
14338  StringRef ReadableName = FnName->getName();
14339 
14340  if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
14341  if (UnaryOp->getOpcode() == UO_AddrOf)
14342  ActionIdx = 1; // If its an address-of operator, just remove it.
14343  if (!PointeeTy->isIncompleteType() &&
14344  (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
14345  ActionIdx = 2; // If the pointee's size is sizeof(char),
14346  // suggest an explicit length.
14347 
14348  // If the function is defined as a builtin macro, do not show macro
14349  // expansion.
14350  SourceLocation SL = SizeOfArg->getExprLoc();
14351  SourceRange DSR = Dest->getSourceRange();
14352  SourceRange SSR = SizeOfArg->getSourceRange();
14353  SourceManager &SM = getSourceManager();
14354 
14355  if (SM.isMacroArgExpansion(SL)) {
14356  ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
14357  SL = SM.getSpellingLoc(SL);
14358  DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
14359  SM.getSpellingLoc(DSR.getEnd()));
14360  SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
14361  SM.getSpellingLoc(SSR.getEnd()));
14362  }
14363 
14364  DiagRuntimeBehavior(SL, SizeOfArg,
14365  PDiag(diag::warn_sizeof_pointer_expr_memaccess)
14366  << ReadableName
14367  << PointeeTy
14368  << DestTy
14369  << DSR
14370  << SSR);
14371  DiagRuntimeBehavior(SL, SizeOfArg,
14372  PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
14373  << ActionIdx
14374  << SSR);
14375 
14376  break;
14377  }
14378  }
14379 
14380  // Also check for cases where the sizeof argument is the exact same
14381  // type as the memory argument, and where it points to a user-defined
14382  // record type.
14383  if (SizeOfArgTy != QualType()) {
14384  if (PointeeTy->isRecordType() &&
14385  Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
14386  DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
14387  PDiag(diag::warn_sizeof_pointer_type_memaccess)
14388  << FnName << SizeOfArgTy << ArgIdx
14389  << PointeeTy << Dest->getSourceRange()
14390  << LenExpr->getSourceRange());
14391  break;
14392  }
14393  }
14394  } else if (DestTy->isArrayType()) {
14395  PointeeTy = DestTy;
14396  }
14397 
14398  if (PointeeTy == QualType())
14399  continue;
14400 
14401  // Always complain about dynamic classes.
14402  bool IsContained;
14403  if (const CXXRecordDecl *ContainedRD =
14404  getContainedDynamicClass(PointeeTy, IsContained)) {
14405 
14406  unsigned OperationType = 0;
14407  const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
14408  // "overwritten" if we're warning about the destination for any call
14409  // but memcmp; otherwise a verb appropriate to the call.
14410  if (ArgIdx != 0 || IsCmp) {
14411  if (BId == Builtin::BImemcpy)
14412  OperationType = 1;
14413  else if(BId == Builtin::BImemmove)
14414  OperationType = 2;
14415  else if (IsCmp)
14416  OperationType = 3;
14417  }
14418 
14419  DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
14420  PDiag(diag::warn_dyn_class_memaccess)
14421  << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
14422  << IsContained << ContainedRD << OperationType
14423  << Call->getCallee()->getSourceRange());
14424  } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
14425  BId != Builtin::BImemset)
14426  DiagRuntimeBehavior(
14427  Dest->getExprLoc(), Dest,
14428  PDiag(diag::warn_arc_object_memaccess)
14429  << ArgIdx << FnName << PointeeTy
14430  << Call->getCallee()->getSourceRange());
14431  else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
14432  if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
14433  RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
14434  DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
14435  PDiag(diag::warn_cstruct_memaccess)
14436  << ArgIdx << FnName << PointeeTy << 0);
14437  SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
14438  } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
14439  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
14440  DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
14441  PDiag(diag::warn_cstruct_memaccess)
14442  << ArgIdx << FnName << PointeeTy << 1);
14443  SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
14444  } else {
14445  continue;
14446  }
14447  } else
14448  continue;
14449 
14450  DiagRuntimeBehavior(
14451  Dest->getExprLoc(), Dest,
14452  PDiag(diag::note_bad_memaccess_silence)
14453  << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
14454  break;
14455  }
14456 }
14457 
14458 // A little helper routine: ignore addition and subtraction of integer literals.
14459 // This intentionally does not ignore all integer constant expressions because
14460 // we don't want to remove sizeof().
14461 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
14462  Ex = Ex->IgnoreParenCasts();
14463 
14464  while (true) {
14465  const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
14466  if (!BO || !BO->isAdditiveOp())
14467  break;
14468 
14469  const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
14470  const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
14471 
14472  if (isa<IntegerLiteral>(RHS))
14473  Ex = LHS;
14474  else if (isa<IntegerLiteral>(LHS))
14475  Ex = RHS;
14476  else
14477  break;
14478  }
14479 
14480  return Ex;
14481 }
14482 
14484  ASTContext &Context) {
14485  // Only handle constant-sized or VLAs, but not flexible members.
14486  if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
14487  // Only issue the FIXIT for arrays of size > 1.
14488  if (CAT->getZExtSize() <= 1)
14489  return false;
14490  } else if (!Ty->isVariableArrayType()) {
14491  return false;
14492  }
14493  return true;
14494 }
14495 
14496 // Warn if the user has made the 'size' argument to strlcpy or strlcat
14497 // be the size of the source, instead of the destination.
14498 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
14499  IdentifierInfo *FnName) {
14500 
14501  // Don't crash if the user has the wrong number of arguments
14502  unsigned NumArgs = Call->getNumArgs();
14503  if ((NumArgs != 3) && (NumArgs != 4))
14504  return;
14505 
14506  const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
14507  const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
14508  const Expr *CompareWithSrc = nullptr;
14509 
14510  if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
14511  Call->getBeginLoc(), Call->getRParenLoc()))
14512  return;
14513 
14514  // Look for 'strlcpy(dst, x, sizeof(x))'
14515  if (const Expr *Ex = getSizeOfExprArg(SizeArg))
14516  CompareWithSrc = Ex;
14517  else {
14518  // Look for 'strlcpy(dst, x, strlen(x))'
14519  if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
14520  if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
14521  SizeCall->getNumArgs() == 1)
14522  CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
14523  }
14524  }
14525 
14526  if (!CompareWithSrc)
14527  return;
14528 
14529  // Determine if the argument to sizeof/strlen is equal to the source
14530  // argument. In principle there's all kinds of things you could do
14531  // here, for instance creating an == expression and evaluating it with
14532  // EvaluateAsBooleanCondition, but this uses a more direct technique:
14533  const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
14534  if (!SrcArgDRE)
14535  return;
14536 
14537  const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
14538  if (!CompareWithSrcDRE ||
14539  SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
14540  return;
14541 
14542  const Expr *OriginalSizeArg = Call->getArg(2);
14543  Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
14544  << OriginalSizeArg->getSourceRange() << FnName;
14545 
14546  // Output a FIXIT hint if the destination is an array (rather than a
14547  // pointer to an array). This could be enhanced to handle some
14548  // pointers if we know the actual size, like if DstArg is 'array+2'
14549  // we could say 'sizeof(array)-2'.
14550  const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
14551  if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
14552  return;
14553 
14554  SmallString<128> sizeString;
14555  llvm::raw_svector_ostream OS(sizeString);
14556  OS << "sizeof(";
14557  DstArg->printPretty(OS, nullptr, getPrintingPolicy());
14558  OS << ")";
14559 
14560  Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
14561  << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
14562  OS.str());
14563 }
14564 
14565 /// Check if two expressions refer to the same declaration.
14566 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
14567  if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
14568  if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
14569  return D1->getDecl() == D2->getDecl();
14570  return false;
14571 }
14572 
14573 static const Expr *getStrlenExprArg(const Expr *E) {
14574  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
14575  const FunctionDecl *FD = CE->getDirectCallee();
14576  if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
14577  return nullptr;
14578  return CE->getArg(0)->IgnoreParenCasts();
14579  }
14580  return nullptr;
14581 }
14582 
14583 // Warn on anti-patterns as the 'size' argument to strncat.
14584 // The correct size argument should look like following:
14585 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
14586 void Sema::CheckStrncatArguments(const CallExpr *CE,
14587  IdentifierInfo *FnName) {
14588  // Don't crash if the user has the wrong number of arguments.
14589  if (CE->getNumArgs() < 3)
14590  return;
14591  const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
14592  const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
14593  const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
14594 
14595  if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
14596  CE->getRParenLoc()))
14597  return;
14598 
14599  // Identify common expressions, which are wrongly used as the size argument
14600  // to strncat and may lead to buffer overflows.
14601  unsigned PatternType = 0;
14602  if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
14603  // - sizeof(dst)
14604  if (referToTheSameDecl(SizeOfArg, DstArg))
14605  PatternType = 1;
14606  // - sizeof(src)
14607  else if (referToTheSameDecl(SizeOfArg, SrcArg))
14608  PatternType = 2;
14609  } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
14610  if (BE->getOpcode() == BO_Sub) {
14611  const Expr *L = BE->getLHS()->IgnoreParenCasts();
14612  const Expr *R = BE->getRHS()->IgnoreParenCasts();
14613  // - sizeof(dst) - strlen(dst)
14614  if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
14616  PatternType = 1;
14617  // - sizeof(src) - (anything)
14618  else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
14619  PatternType = 2;
14620  }
14621  }
14622 
14623  if (PatternType == 0)
14624  return;
14625 
14626  // Generate the diagnostic.
14627  SourceLocation SL = LenArg->getBeginLoc();
14628  SourceRange SR = LenArg->getSourceRange();
14629  SourceManager &SM = getSourceManager();
14630 
14631  // If the function is defined as a builtin macro, do not show macro expansion.
14632  if (SM.isMacroArgExpansion(SL)) {
14633  SL = SM.getSpellingLoc(SL);
14634  SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
14635  SM.getSpellingLoc(SR.getEnd()));
14636  }
14637 
14638  // Check if the destination is an array (rather than a pointer to an array).
14639  QualType DstTy = DstArg->getType();
14640  bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
14641  Context);
14642  if (!isKnownSizeArray) {
14643  if (PatternType == 1)
14644  Diag(SL, diag::warn_strncat_wrong_size) << SR;
14645  else
14646  Diag(SL, diag::warn_strncat_src_size) << SR;
14647  return;
14648  }
14649 
14650  if (PatternType == 1)
14651  Diag(SL, diag::warn_strncat_large_size) << SR;
14652  else
14653  Diag(SL, diag::warn_strncat_src_size) << SR;
14654 
14655  SmallString<128> sizeString;
14656  llvm::raw_svector_ostream OS(sizeString);
14657  OS << "sizeof(";
14658  DstArg->printPretty(OS, nullptr, getPrintingPolicy());
14659  OS << ") - ";
14660  OS << "strlen(";
14661  DstArg->printPretty(OS, nullptr, getPrintingPolicy());
14662  OS << ") - 1";
14663 
14664  Diag(SL, diag::note_strncat_wrong_size)
14665  << FixItHint::CreateReplacement(SR, OS.str());
14666 }
14667 
14668 namespace {
14669 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
14670  const UnaryOperator *UnaryExpr, const Decl *D) {
14671  if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
14672  S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
14673  << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
14674  return;
14675  }
14676 }
14677 
14678 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
14679  const UnaryOperator *UnaryExpr) {
14680  if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
14681  const Decl *D = Lvalue->getDecl();
14682  if (isa<DeclaratorDecl>(D))
14683  if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
14684  return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
14685  }
14686 
14687  if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
14688  return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
14689  Lvalue->getMemberDecl());
14690 }
14691 
14692 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
14693  const UnaryOperator *UnaryExpr) {
14694  const auto *Lambda = dyn_cast<LambdaExpr>(
14695  UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
14696  if (!Lambda)
14697  return;
14698 
14699  S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
14700  << CalleeName << 2 /*object: lambda expression*/;
14701 }
14702 
14703 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
14704  const DeclRefExpr *Lvalue) {
14705  const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
14706  if (Var == nullptr)
14707  return;
14708 
14709  S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
14710  << CalleeName << 0 /*object: */ << Var;
14711 }
14712 
14713 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
14714  const CastExpr *Cast) {
14715  SmallString<128> SizeString;
14716  llvm::raw_svector_ostream OS(SizeString);
14717 
14718  clang::CastKind Kind = Cast->getCastKind();
14719  if (Kind == clang::CK_BitCast &&
14720  !Cast->getSubExpr()->getType()->isFunctionPointerType())
14721  return;
14722  if (Kind == clang::CK_IntegralToPointer &&
14723  !isa<IntegerLiteral>(
14724  Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
14725  return;
14726 
14727  switch (Cast->getCastKind()) {
14728  case clang::CK_BitCast:
14729  case clang::CK_IntegralToPointer:
14730  case clang::CK_FunctionToPointerDecay:
14731  OS << '\'';
14732  Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
14733  OS << '\'';
14734  break;
14735  default:
14736  return;
14737  }
14738 
14739  S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
14740  << CalleeName << 0 /*object: */ << OS.str();
14741 }
14742 } // namespace
14743 
14744 /// Alerts the user that they are attempting to free a non-malloc'd object.
14745 void Sema::CheckFreeArguments(const CallExpr *E) {
14746  const std::string CalleeName =
14747  cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
14748 
14749  { // Prefer something that doesn't involve a cast to make things simpler.
14750  const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
14751  if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
14752  switch (UnaryExpr->getOpcode()) {
14753  case UnaryOperator::Opcode::UO_AddrOf:
14754  return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
14755  case UnaryOperator::Opcode::UO_Plus:
14756  return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
14757  default:
14758  break;
14759  }
14760 
14761  if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
14762  if (Lvalue->getType()->isArrayType())
14763  return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
14764 
14765  if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
14766  Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
14767  << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
14768  return;
14769  }
14770 
14771  if (isa<BlockExpr>(Arg)) {
14772  Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
14773  << CalleeName << 1 /*object: block*/;
14774  return;
14775  }
14776  }
14777  // Maybe the cast was important, check after the other cases.
14778  if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
14779  return CheckFreeArgumentsCast(*this, CalleeName, Cast);
14780 }
14781 
14782 void
14783 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
14784  SourceLocation ReturnLoc,
14785  bool isObjCMethod,
14786  const AttrVec *Attrs,
14787  const FunctionDecl *FD) {
14788  // Check if the return value is null but should not be.
14789  if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
14790  (!isObjCMethod && isNonNullType(lhsType))) &&
14791  CheckNonNullExpr(*this, RetValExp))
14792  Diag(ReturnLoc, diag::warn_null_ret)
14793  << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
14794 
14795  // C++11 [basic.stc.dynamic.allocation]p4:
14796  // If an allocation function declared with a non-throwing
14797  // exception-specification fails to allocate storage, it shall return
14798  // a null pointer. Any other allocation function that fails to allocate
14799  // storage shall indicate failure only by throwing an exception [...]
14800  if (FD) {
14802  if (Op == OO_New || Op == OO_Array_New) {
14803  const FunctionProtoType *Proto
14804  = FD->getType()->castAs<FunctionProtoType>();
14805  if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
14806  CheckNonNullExpr(*this, RetValExp))
14807  Diag(ReturnLoc, diag::warn_operator_new_returns_null)
14808  << FD << getLangOpts().CPlusPlus11;
14809  }
14810  }
14811 
14812  if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
14813  Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
14814  }
14815 
14816  // PPC MMA non-pointer types are not allowed as return type. Checking the type
14817  // here prevent the user from using a PPC MMA type as trailing return type.
14818  if (Context.getTargetInfo().getTriple().isPPC64())
14819  CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
14820 }
14821 
14822 /// Check for comparisons of floating-point values using == and !=. Issue a
14823 /// warning if the comparison is not likely to do what the programmer intended.
14827  return;
14828 
14829  // Match and capture subexpressions such as "(float) X == 0.1".
14830  FloatingLiteral *FPLiteral;
14831  CastExpr *FPCast;
14832  auto getCastAndLiteral = [&FPLiteral, &FPCast](Expr *L, Expr *R) {
14833  FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
14834  FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
14835  return FPLiteral && FPCast;
14836  };
14837 
14838  if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
14839  auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
14840  auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
14841  if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
14842  TargetTy->isFloatingPoint()) {
14843  bool Lossy;
14844  llvm::APFloat TargetC = FPLiteral->getValue();
14845  TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
14846  llvm::APFloat::rmNearestTiesToEven, &Lossy);
14847  if (Lossy) {
14848  // If the literal cannot be represented in the source type, then a
14849  // check for == is always false and check for != is always true.
14850  Diag(Loc, diag::warn_float_compare_literal)
14851  << (Opcode == BO_EQ) << QualType(SourceTy, 0)
14852  << LHS->getSourceRange() << RHS->getSourceRange();
14853  return;
14854  }
14855  }
14856  }
14857 
14858  // Match a more general floating-point equality comparison (-Wfloat-equal).
14859  Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
14860  Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
14861 
14862  // Special case: check for x == x (which is OK).
14863  // Do not emit warnings for such cases.
14864  if (auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
14865  if (auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
14866  if (DRL->getDecl() == DRR->getDecl())
14867  return;
14868 
14869  // Special case: check for comparisons against literals that can be exactly
14870  // represented by APFloat. In such cases, do not emit a warning. This
14871  // is a heuristic: often comparison against such literals are used to
14872  // detect if a value in a variable has not changed. This clearly can
14873  // lead to false negatives.
14874  if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
14875  if (FLL->isExact())
14876  return;
14877  } else
14878  if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
14879  if (FLR->isExact())
14880  return;
14881 
14882  // Check for comparisons with builtin types.
14883  if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
14884  if (CL->getBuiltinCallee())
14885  return;
14886 
14887  if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
14888  if (CR->getBuiltinCallee())
14889  return;
14890 
14891  // Emit the diagnostic.
14892  Diag(Loc, diag::warn_floatingpoint_eq)
14893  << LHS->getSourceRange() << RHS->getSourceRange();
14894 }
14895 
14896 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
14897 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
14898 
14899 namespace {
14900 
14901 /// Structure recording the 'active' range of an integer-valued
14902 /// expression.
14903 struct IntRange {
14904  /// The number of bits active in the int. Note that this includes exactly one
14905  /// sign bit if !NonNegative.
14906  unsigned Width;
14907 
14908  /// True if the int is known not to have negative values. If so, all leading
14909  /// bits before Width are known zero, otherwise they are known to be the
14910  /// same as the MSB within Width.
14911  bool NonNegative;
14912 
14913  IntRange(unsigned Width, bool NonNegative)
14914  : Width(Width), NonNegative(NonNegative) {}
14915 
14916  /// Number of bits excluding the sign bit.
14917  unsigned valueBits() const {
14918  return NonNegative ? Width : Width - 1;
14919  }
14920 
14921  /// Returns the range of the bool type.
14922  static IntRange forBoolType() {
14923  return IntRange(1, true);
14924  }
14925 
14926  /// Returns the range of an opaque value of the given integral type.
14927  static IntRange forValueOfType(ASTContext &C, QualType T) {
14928  return forValueOfCanonicalType(C,
14930  }
14931 
14932  /// Returns the range of an opaque value of a canonical integral type.
14933  static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
14934  assert(T->isCanonicalUnqualified());
14935 
14936  if (const VectorType *VT = dyn_cast<VectorType>(T))
14937  T = VT->getElementType().getTypePtr();
14938  if (const ComplexType *CT = dyn_cast<ComplexType>(T))
14939  T = CT->getElementType().getTypePtr();
14940  if (const AtomicType *AT = dyn_cast<AtomicType>(T))
14941  T = AT->getValueType().getTypePtr();
14942 
14943  if (!C.getLangOpts().CPlusPlus) {
14944  // For enum types in C code, use the underlying datatype.
14945  if (const EnumType *ET = dyn_cast<EnumType>(T))
14946  T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
14947  } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
14948  // For enum types in C++, use the known bit width of the enumerators.
14949  EnumDecl *Enum = ET->getDecl();
14950  // In C++11, enums can have a fixed underlying type. Use this type to
14951  // compute the range.
14952  if (Enum->isFixed()) {
14953  return IntRange(C.getIntWidth(QualType(T, 0)),
14955  }
14956 
14957  unsigned NumPositive = Enum->getNumPositiveBits();
14958  unsigned NumNegative = Enum->getNumNegativeBits();
14959 
14960  if (NumNegative == 0)
14961  return IntRange(NumPositive, true/*NonNegative*/);
14962  else
14963  return IntRange(std::max(NumPositive + 1, NumNegative),
14964  false/*NonNegative*/);
14965  }
14966 
14967  if (const auto *EIT = dyn_cast<BitIntType>(T))
14968  return IntRange(EIT->getNumBits(), EIT->isUnsigned());
14969 
14970  const BuiltinType *BT = cast<BuiltinType>(T);
14971  assert(BT->isInteger());
14972 
14973  return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
14974  }
14975 
14976  /// Returns the "target" range of a canonical integral type, i.e.
14977  /// the range of values expressible in the type.
14978  ///
14979  /// This matches forValueOfCanonicalType except that enums have the
14980  /// full range of their type, not the range of their enumerators.
14981  static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
14982  assert(T->isCanonicalUnqualified());
14983 
14984  if (const VectorType *VT = dyn_cast<VectorType>(T))
14985  T = VT->getElementType().getTypePtr();
14986  if (const ComplexType *CT = dyn_cast<ComplexType>(T))
14987  T = CT->getElementType().getTypePtr();
14988  if (const AtomicType *AT = dyn_cast<AtomicType>(T))
14989  T = AT->getValueType().getTypePtr();
14990  if (const EnumType *ET = dyn_cast<EnumType>(T))
14991  T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
14992 
14993  if (const auto *EIT = dyn_cast<BitIntType>(T))
14994  return IntRange(EIT->getNumBits(), EIT->isUnsigned());
14995 
14996  const BuiltinType *BT = cast<BuiltinType>(T);
14997  assert(BT->isInteger());
14998 
14999  return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
15000  }
15001 
15002  /// Returns the supremum of two ranges: i.e. their conservative merge.
15003  static IntRange join(IntRange L, IntRange R) {
15004  bool Unsigned = L.NonNegative && R.NonNegative;
15005  return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
15006  L.NonNegative && R.NonNegative);
15007  }
15008 
15009  /// Return the range of a bitwise-AND of the two ranges.
15010  static IntRange bit_and(IntRange L, IntRange R) {
15011  unsigned Bits = std::max(L.Width, R.Width);
15012  bool NonNegative = false;
15013  if (L.NonNegative) {
15014  Bits = std::min(Bits, L.Width);
15015  NonNegative = true;
15016  }
15017  if (R.NonNegative) {
15018  Bits = std::min(Bits, R.Width);
15019  NonNegative = true;
15020  }
15021  return IntRange(Bits, NonNegative);
15022  }
15023 
15024  /// Return the range of a sum of the two ranges.
15025  static IntRange sum(IntRange L, IntRange R) {
15026  bool Unsigned = L.NonNegative && R.NonNegative;
15027  return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
15028  Unsigned);
15029  }
15030 
15031  /// Return the range of a difference of the two ranges.
15032  static IntRange difference(IntRange L, IntRange R) {
15033  // We need a 1-bit-wider range if:
15034  // 1) LHS can be negative: least value can be reduced.
15035  // 2) RHS can be negative: greatest value can be increased.
15036  bool CanWiden = !L.NonNegative || !R.NonNegative;
15037  bool Unsigned = L.NonNegative && R.Width == 0;
15038  return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
15039  !Unsigned,
15040  Unsigned);
15041  }
15042 
15043  /// Return the range of a product of the two ranges.
15044  static IntRange product(IntRange L, IntRange R) {
15045  // If both LHS and RHS can be negative, we can form
15046  // -2^L * -2^R = 2^(L + R)
15047  // which requires L + R + 1 value bits to represent.
15048  bool CanWiden = !L.NonNegative && !R.NonNegative;
15049  bool Unsigned = L.NonNegative && R.NonNegative;
15050  return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
15051  Unsigned);
15052  }
15053 
15054  /// Return the range of a remainder operation between the two ranges.
15055  static IntRange rem(IntRange L, IntRange R) {
15056  // The result of a remainder can't be larger than the result of
15057  // either side. The sign of the result is the sign of the LHS.
15058  bool Unsigned = L.NonNegative;
15059  return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
15060  Unsigned);
15061  }
15062 };
15063 
15064 } // namespace
15065 
15066 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
15067  unsigned MaxWidth) {
15068  if (value.isSigned() && value.isNegative())
15069  return IntRange(value.getSignificantBits(), false);
15070 
15071  if (value.getBitWidth() > MaxWidth)
15072  value = value.trunc(MaxWidth);
15073 
15074  // isNonNegative() just checks the sign bit without considering
15075  // signedness.
15076  return IntRange(value.getActiveBits(), true);
15077 }
15078 
15079 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
15080  unsigned MaxWidth) {
15081  if (result.isInt())
15082  return GetValueRange(C, result.getInt(), MaxWidth);
15083 
15084  if (result.isVector()) {
15085  IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
15086  for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
15087  IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
15088  R = IntRange::join(R, El);
15089  }
15090  return R;
15091  }
15092 
15093  if (result.isComplexInt()) {
15094  IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
15095  IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
15096  return IntRange::join(R, I);
15097  }
15098 
15099  // This can happen with lossless casts to intptr_t of "based" lvalues.
15100  // Assume it might use arbitrary bits.
15101  // FIXME: The only reason we need to pass the type in here is to get
15102  // the sign right on this one case. It would be nice if APValue
15103  // preserved this.
15104  assert(result.isLValue() || result.isAddrLabelDiff());
15105  return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
15106 }
15107 
15108 static QualType GetExprType(const Expr *E) {
15109  QualType Ty = E->getType();
15110  if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
15111  Ty = AtomicRHS->getValueType();
15112  return Ty;
15113 }
15114 
15115 /// Pseudo-evaluate the given integer expression, estimating the
15116 /// range of values it might take.
15117 ///
15118 /// \param MaxWidth The width to which the value will be truncated.
15119 /// \param Approximate If \c true, return a likely range for the result: in
15120 /// particular, assume that arithmetic on narrower types doesn't leave
15121 /// those types. If \c false, return a range including all possible
15122 /// result values.
15123 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
15124  bool InConstantContext, bool Approximate) {
15125  E = E->IgnoreParens();
15126 
15127  // Try a full evaluation first.
15128  Expr::EvalResult result;
15129  if (E->EvaluateAsRValue(result, C, InConstantContext))
15130  return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
15131 
15132  // I think we only want to look through implicit casts here; if the
15133  // user has an explicit widening cast, we should treat the value as
15134  // being of the new, wider type.
15135  if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
15136  if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
15137  return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
15138  Approximate);
15139 
15140  IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
15141 
15142  bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
15143  CE->getCastKind() == CK_BooleanToSignedIntegral;
15144 
15145  // Assume that non-integer casts can span the full range of the type.
15146  if (!isIntegerCast)
15147  return OutputTypeRange;
15148 
15149  IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
15150  std::min(MaxWidth, OutputTypeRange.Width),
15151  InConstantContext, Approximate);
15152 
15153  // Bail out if the subexpr's range is as wide as the cast type.
15154  if (SubRange.Width >= OutputTypeRange.Width)
15155  return OutputTypeRange;
15156 
15157  // Otherwise, we take the smaller width, and we're non-negative if
15158  // either the output type or the subexpr is.
15159  return IntRange(SubRange.Width,
15160  SubRange.NonNegative || OutputTypeRange.NonNegative);
15161  }
15162 
15163  if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
15164  // If we can fold the condition, just take that operand.
15165  bool CondResult;
15166  if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
15167  return GetExprRange(C,
15168  CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
15169  MaxWidth, InConstantContext, Approximate);
15170 
15171  // Otherwise, conservatively merge.
15172  // GetExprRange requires an integer expression, but a throw expression
15173  // results in a void type.
15174  Expr *E = CO->getTrueExpr();
15175  IntRange L = E->getType()->isVoidType()
15176  ? IntRange{0, true}
15177  : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
15178  E = CO->getFalseExpr();
15179  IntRange R = E->getType()->isVoidType()
15180  ? IntRange{0, true}
15181  : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
15182  return IntRange::join(L, R);
15183  }
15184 
15185  if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
15186  IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
15187 
15188  switch (BO->getOpcode()) {
15189  case BO_Cmp:
15190  llvm_unreachable("builtin <=> should have class type");
15191 
15192  // Boolean-valued operations are single-bit and positive.
15193  case BO_LAnd:
15194  case BO_LOr:
15195  case BO_LT:
15196  case BO_GT:
15197  case BO_LE:
15198  case BO_GE:
15199  case BO_EQ:
15200  case BO_NE:
15201  return IntRange::forBoolType();
15202 
15203  // The type of the assignments is the type of the LHS, so the RHS
15204  // is not necessarily the same type.
15205  case BO_MulAssign:
15206  case BO_DivAssign:
15207  case BO_RemAssign:
15208  case BO_AddAssign:
15209  case BO_SubAssign:
15210  case BO_XorAssign:
15211  case BO_OrAssign:
15212  // TODO: bitfields?
15213  return IntRange::forValueOfType(C, GetExprType(E));
15214 
15215  // Simple assignments just pass through the RHS, which will have
15216  // been coerced to the LHS type.
15217  case BO_Assign:
15218  // TODO: bitfields?
15219  return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
15220  Approximate);
15221 
15222  // Operations with opaque sources are black-listed.
15223  case BO_PtrMemD:
15224  case BO_PtrMemI:
15225  return IntRange::forValueOfType(C, GetExprType(E));
15226 
15227  // Bitwise-and uses the *infinum* of the two source ranges.
15228  case BO_And:
15229  case BO_AndAssign:
15230  Combine = IntRange::bit_and;
15231  break;
15232 
15233  // Left shift gets black-listed based on a judgement call.
15234  case BO_Shl:
15235  // ...except that we want to treat '1 << (blah)' as logically
15236  // positive. It's an important idiom.
15237  if (IntegerLiteral *I
15238  = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
15239  if (I->getValue() == 1) {
15240  IntRange R = IntRange::forValueOfType(C, GetExprType(E));
15241  return IntRange(R.Width, /*NonNegative*/ true);
15242  }
15243  }
15244  [[fallthrough]];
15245 
15246  case BO_ShlAssign:
15247  return IntRange::forValueOfType(C, GetExprType(E));
15248 
15249  // Right shift by a constant can narrow its left argument.
15250  case BO_Shr:
15251  case BO_ShrAssign: {
15252  IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
15253  Approximate);
15254 
15255  // If the shift amount is a positive constant, drop the width by
15256  // that much.
15257  if (std::optional<llvm::APSInt> shift =
15258  BO->getRHS()->getIntegerConstantExpr(C)) {
15259  if (shift->isNonNegative()) {
15260  if (shift->uge(L.Width))
15261  L.Width = (L.NonNegative ? 0 : 1);
15262  else
15263  L.Width -= shift->getZExtValue();
15264  }
15265  }
15266 
15267  return L;
15268  }
15269 
15270  // Comma acts as its right operand.
15271  case BO_Comma:
15272  return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
15273  Approximate);
15274 
15275  case BO_Add:
15276  if (!Approximate)
15277  Combine = IntRange::sum;
15278  break;
15279 
15280  case BO_Sub:
15281  if (BO->getLHS()->getType()->isPointerType())
15282  return IntRange::forValueOfType(C, GetExprType(E));
15283  if (!Approximate)
15284  Combine = IntRange::difference;
15285  break;
15286 
15287  case BO_Mul:
15288  if (!Approximate)
15289  Combine = IntRange::product;
15290  break;
15291 
15292  // The width of a division result is mostly determined by the size
15293  // of the LHS.
15294  case BO_Div: {
15295  // Don't 'pre-truncate' the operands.
15296  unsigned opWidth = C.getIntWidth(GetExprType(E));
15297  IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
15298  Approximate);
15299 
15300  // If the divisor is constant, use that.
15301  if (std::optional<llvm::APSInt> divisor =
15302  BO->getRHS()->getIntegerConstantExpr(C)) {
15303  unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
15304  if (log2 >= L.Width)
15305  L.Width = (L.NonNegative ? 0 : 1);
15306  else
15307  L.Width = std::min(L.Width - log2, MaxWidth);
15308  return L;
15309  }
15310 
15311  // Otherwise, just use the LHS's width.
15312  // FIXME: This is wrong if the LHS could be its minimal value and the RHS
15313  // could be -1.
15314  IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
15315  Approximate);
15316  return IntRange(L.Width, L.NonNegative && R.NonNegative);
15317  }
15318 
15319  case BO_Rem:
15320  Combine = IntRange::rem;
15321  break;
15322 
15323  // The default behavior is okay for these.
15324  case BO_Xor:
15325  case BO_Or:
15326  break;
15327  }
15328 
15329  // Combine the two ranges, but limit the result to the type in which we
15330  // performed the computation.
15331  QualType T = GetExprType(E);
15332  unsigned opWidth = C.getIntWidth(T);
15333  IntRange L =
15334  GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
15335  IntRange R =
15336  GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
15337  IntRange C = Combine(L, R);
15338  C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
15339  C.Width = std::min(C.Width, MaxWidth);
15340  return C;
15341  }
15342 
15343  if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
15344  switch (UO->getOpcode()) {
15345  // Boolean-valued operations are white-listed.
15346  case UO_LNot:
15347  return IntRange::forBoolType();
15348 
15349  // Operations with opaque sources are black-listed.
15350  case UO_Deref:
15351  case UO_AddrOf: // should be impossible
15352  return IntRange::forValueOfType(C, GetExprType(E));
15353 
15354  default:
15355  return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
15356  Approximate);
15357  }
15358  }
15359 
15360  if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
15361  return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
15362  Approximate);
15363 
15364  if (const auto *BitField = E->getSourceBitField())
15365  return IntRange(BitField->getBitWidthValue(C),
15366  BitField->getType()->isUnsignedIntegerOrEnumerationType());
15367 
15368  return IntRange::forValueOfType(C, GetExprType(E));
15369 }
15370 
15371 static IntRange GetExprRange(ASTContext &C, const Expr *E,
15372  bool InConstantContext, bool Approximate) {
15373  return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
15374  Approximate);
15375 }
15376 
15377 /// Checks whether the given value, which currently has the given
15378 /// source semantics, has the same value when coerced through the
15379 /// target semantics.
15380 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
15381  const llvm::fltSemantics &Src,
15382  const llvm::fltSemantics &Tgt) {
15383  llvm::APFloat truncated = value;
15384 
15385  bool ignored;
15386  truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
15387  truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
15388 
15389  return truncated.bitwiseIsEqual(value);
15390 }
15391 
15392 /// Checks whether the given value, which currently has the given
15393 /// source semantics, has the same value when coerced through the
15394 /// target semantics.
15395 ///
15396 /// The value might be a vector of floats (or a complex number).
15397 static bool IsSameFloatAfterCast(const APValue &value,
15398  const llvm::fltSemantics &Src,
15399  const llvm::fltSemantics &Tgt) {
15400  if (value.isFloat())
15401  return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
15402 
15403  if (value.isVector()) {
15404  for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
15405  if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
15406  return false;
15407  return true;
15408  }
15409 
15410  assert(value.isComplexFloat());
15411  return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
15412  IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
15413 }
15414 
15415 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
15416  bool IsListInit = false);
15417 
15418 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
15419  // Suppress cases where we are comparing against an enum constant.
15420  if (const DeclRefExpr *DR =
15421  dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
15422  if (isa<EnumConstantDecl>(DR->getDecl()))
15423  return true;
15424 
15425  // Suppress cases where the value is expanded from a macro, unless that macro
15426  // is how a language represents a boolean literal. This is the case in both C
15427  // and Objective-C.
15428  SourceLocation BeginLoc = E->getBeginLoc();
15429  if (BeginLoc.isMacroID()) {
15430  StringRef MacroName = Lexer::getImmediateMacroName(
15431  BeginLoc, S.getSourceManager(), S.getLangOpts());
15432  return MacroName != "YES" && MacroName != "NO" &&
15433  MacroName != "true" && MacroName != "false";
15434  }
15435 
15436  return false;
15437 }
15438 
15440  return E->getType()->isIntegerType() &&
15441  (!E->getType()->isSignedIntegerType() ||
15443 }
15444 
15445 namespace {
15446 /// The promoted range of values of a type. In general this has the
15447 /// following structure:
15448 ///
15449 /// |-----------| . . . |-----------|
15450 /// ^ ^ ^ ^
15451 /// Min HoleMin HoleMax Max
15452 ///
15453 /// ... where there is only a hole if a signed type is promoted to unsigned
15454 /// (in which case Min and Max are the smallest and largest representable
15455 /// values).
15456 struct PromotedRange {
15457  // Min, or HoleMax if there is a hole.
15458  llvm::APSInt PromotedMin;
15459  // Max, or HoleMin if there is a hole.
15460  llvm::APSInt PromotedMax;
15461 
15462  PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
15463  if (R.Width == 0)
15464  PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
15465  else if (R.Width >= BitWidth && !Unsigned) {
15466  // Promotion made the type *narrower*. This happens when promoting
15467  // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
15468  // Treat all values of 'signed int' as being in range for now.
15469  PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
15470  PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
15471  } else {
15472  PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
15473  .extOrTrunc(BitWidth);
15474  PromotedMin.setIsUnsigned(Unsigned);
15475 
15476  PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
15477  .extOrTrunc(BitWidth);
15478  PromotedMax.setIsUnsigned(Unsigned);
15479  }
15480  }
15481 
15482  // Determine whether this range is contiguous (has no hole).
15483  bool isContiguous() const { return PromotedMin <= PromotedMax; }
15484 
15485  // Where a constant value is within the range.
15486  enum ComparisonResult {
15487  LT = 0x1,
15488  LE = 0x2,
15489  GT = 0x4,
15490  GE = 0x8,
15491  EQ = 0x10,
15492  NE = 0x20,
15493  InRangeFlag = 0x40,
15494 
15495  Less = LE | LT | NE,
15496  Min = LE | InRangeFlag,
15497  InRange = InRangeFlag,
15498  Max = GE | InRangeFlag,
15499  Greater = GE | GT | NE,
15500 
15501  OnlyValue = LE | GE | EQ | InRangeFlag,
15502  InHole = NE
15503  };
15504 
15505  ComparisonResult compare(const llvm::APSInt &Value) const {
15506  assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
15507  Value.isUnsigned() == PromotedMin.isUnsigned());
15508  if (!isContiguous()) {
15509  assert(Value.isUnsigned() && "discontiguous range for signed compare");
15510  if (Value.isMinValue()) return Min;
15511  if (Value.isMaxValue()) return Max;
15512  if (Value >= PromotedMin) return InRange;
15513  if (Value <= PromotedMax) return InRange;
15514  return InHole;
15515  }
15516 
15517  switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
15518  case -1: return Less;
15519  case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
15520  case 1:
15521  switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
15522  case -1: return InRange;
15523  case 0: return Max;
15524  case 1: return Greater;
15525  }
15526  }
15527 
15528  llvm_unreachable("impossible compare result");
15529  }
15530 
15531  static std::optional<StringRef>
15532  constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
15533  if (Op == BO_Cmp) {
15534  ComparisonResult LTFlag = LT, GTFlag = GT;
15535  if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
15536 
15537  if (R & EQ) return StringRef("'std::strong_ordering::equal'");
15538  if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
15539  if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
15540  return std::nullopt;
15541  }
15542 
15543  ComparisonResult TrueFlag, FalseFlag;
15544  if (Op == BO_EQ) {
15545  TrueFlag = EQ;
15546  FalseFlag = NE;
15547  } else if (Op == BO_NE) {
15548  TrueFlag = NE;
15549  FalseFlag = EQ;
15550  } else {
15551  if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
15552  TrueFlag = LT;
15553  FalseFlag = GE;
15554  } else {
15555  TrueFlag = GT;
15556  FalseFlag = LE;
15557  }
15558  if (Op == BO_GE || Op == BO_LE)
15559  std::swap(TrueFlag, FalseFlag);
15560  }
15561  if (R & TrueFlag)
15562  return StringRef("true");
15563  if (R & FalseFlag)
15564  return StringRef("false");
15565  return std::nullopt;
15566  }
15567 };
15568 }
15569 
15570 static bool HasEnumType(Expr *E) {
15571  // Strip off implicit integral promotions.
15572  while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
15573  if (ICE->getCastKind() != CK_IntegralCast &&
15574  ICE->getCastKind() != CK_NoOp)
15575  break;
15576  E = ICE->getSubExpr();
15577  }
15578 
15579  return E->getType()->isEnumeralType();
15580 }
15581 
15582 static int classifyConstantValue(Expr *Constant) {
15583  // The values of this enumeration are used in the diagnostics
15584  // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
15585  enum ConstantValueKind {
15586  Miscellaneous = 0,
15587  LiteralTrue,
15588  LiteralFalse
15589  };
15590  if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
15591  return BL->getValue() ? ConstantValueKind::LiteralTrue
15592  : ConstantValueKind::LiteralFalse;
15593  return ConstantValueKind::Miscellaneous;
15594 }
15595 
15597  Expr *Constant, Expr *Other,
15598  const llvm::APSInt &Value,
15599  bool RhsConstant) {
15600  if (S.inTemplateInstantiation())
15601  return false;
15602 
15603  Expr *OriginalOther = Other;
15604 
15605  Constant = Constant->IgnoreParenImpCasts();
15606  Other = Other->IgnoreParenImpCasts();
15607 
15608  // Suppress warnings on tautological comparisons between values of the same
15609  // enumeration type. There are only two ways we could warn on this:
15610  // - If the constant is outside the range of representable values of
15611  // the enumeration. In such a case, we should warn about the cast
15612  // to enumeration type, not about the comparison.
15613  // - If the constant is the maximum / minimum in-range value. For an
15614  // enumeratin type, such comparisons can be meaningful and useful.
15615  if (Constant->getType()->isEnumeralType() &&
15616  S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
15617  return false;
15618 
15619  IntRange OtherValueRange = GetExprRange(
15620  S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
15621 
15622  QualType OtherT = Other->getType();
15623  if (const auto *AT = OtherT->getAs<AtomicType>())
15624  OtherT = AT->getValueType();
15625  IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
15626 
15627  // Special case for ObjC BOOL on targets where its a typedef for a signed char
15628  // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
15629  bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
15630  S.NSAPIObj->isObjCBOOLType(OtherT) &&
15631  OtherT->isSpecificBuiltinType(BuiltinType::SChar);
15632 
15633  // Whether we're treating Other as being a bool because of the form of
15634  // expression despite it having another type (typically 'int' in C).
15635  bool OtherIsBooleanDespiteType =
15636  !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
15637  if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
15638  OtherTypeRange = OtherValueRange = IntRange::forBoolType();
15639 
15640  // Check if all values in the range of possible values of this expression
15641  // lead to the same comparison outcome.
15642  PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
15643  Value.isUnsigned());
15644  auto Cmp = OtherPromotedValueRange.compare(Value);
15645  auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
15646  if (!Result)
15647  return false;
15648 
15649  // Also consider the range determined by the type alone. This allows us to
15650  // classify the warning under the proper diagnostic group.
15651  bool TautologicalTypeCompare = false;
15652  {
15653  PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
15654  Value.isUnsigned());
15655  auto TypeCmp = OtherPromotedTypeRange.compare(Value);
15656  if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
15657  RhsConstant)) {
15658  TautologicalTypeCompare = true;
15659  Cmp = TypeCmp;
15660  Result = TypeResult;
15661  }
15662  }
15663 
15664  // Don't warn if the non-constant operand actually always evaluates to the
15665  // same value.
15666  if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
15667  return false;
15668 
15669  // Suppress the diagnostic for an in-range comparison if the constant comes
15670  // from a macro or enumerator. We don't want to diagnose
15671  //
15672  // some_long_value <= INT_MAX
15673  //
15674  // when sizeof(int) == sizeof(long).
15675  bool InRange = Cmp & PromotedRange::InRangeFlag;
15676  if (InRange && IsEnumConstOrFromMacro(S, Constant))
15677  return false;
15678 
15679  // A comparison of an unsigned bit-field against 0 is really a type problem,
15680  // even though at the type level the bit-field might promote to 'signed int'.
15681  if (Other->refersToBitField() && InRange && Value == 0 &&
15682  Other->getType()->isUnsignedIntegerOrEnumerationType())
15683  TautologicalTypeCompare = true;
15684 
15685  // If this is a comparison to an enum constant, include that
15686  // constant in the diagnostic.
15687  const EnumConstantDecl *ED = nullptr;
15688  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
15689  ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
15690 
15691  // Should be enough for uint128 (39 decimal digits)
15692  SmallString<64> PrettySourceValue;
15693  llvm::raw_svector_ostream OS(PrettySourceValue);
15694  if (ED) {
15695  OS << '\'' << *ED << "' (" << Value << ")";
15696  } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
15697  Constant->IgnoreParenImpCasts())) {
15698  OS << (BL->getValue() ? "YES" : "NO");
15699  } else {
15700  OS << Value;
15701  }
15702 
15703  if (!TautologicalTypeCompare) {
15704  S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
15705  << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
15706  << E->getOpcodeStr() << OS.str() << *Result
15707  << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
15708  return true;
15709  }
15710 
15711  if (IsObjCSignedCharBool) {
15713  S.PDiag(diag::warn_tautological_compare_objc_bool)
15714  << OS.str() << *Result);
15715  return true;
15716  }
15717 
15718  // FIXME: We use a somewhat different formatting for the in-range cases and
15719  // cases involving boolean values for historical reasons. We should pick a
15720  // consistent way of presenting these diagnostics.
15721  if (!InRange || Other->isKnownToHaveBooleanValue()) {
15722 
15724  E->getOperatorLoc(), E,
15725  S.PDiag(!InRange ? diag::warn_out_of_range_compare
15726  : diag::warn_tautological_bool_compare)
15727  << OS.str() << classifyConstantValue(Constant) << OtherT
15728  << OtherIsBooleanDespiteType << *Result
15729  << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
15730  } else {
15731  bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
15732  unsigned Diag =
15733  (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
15734  ? (HasEnumType(OriginalOther)
15735  ? diag::warn_unsigned_enum_always_true_comparison
15736  : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
15737  : diag::warn_unsigned_always_true_comparison)
15738  : diag::warn_tautological_constant_compare;
15739 
15740  S.Diag(E->getOperatorLoc(), Diag)
15741  << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
15742  << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
15743  }
15744 
15745  return true;
15746 }
15747 
15748 /// Analyze the operands of the given comparison. Implements the
15749 /// fallback case from AnalyzeComparison.
15753 }
15754 
15755 /// Implements -Wsign-compare.
15756 ///
15757 /// \param E the binary operator to check for warnings
15759  // The type the comparison is being performed in.
15760  QualType T = E->getLHS()->getType();
15761 
15762  // Only analyze comparison operators where both sides have been converted to
15763  // the same type.
15764  if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
15765  return AnalyzeImpConvsInComparison(S, E);
15766 
15767  // Don't analyze value-dependent comparisons directly.
15768  if (E->isValueDependent())
15769  return AnalyzeImpConvsInComparison(S, E);
15770 
15771  Expr *LHS = E->getLHS();
15772  Expr *RHS = E->getRHS();
15773 
15774  if (T->isIntegralType(S.Context)) {
15775  std::optional<llvm::APSInt> RHSValue =
15777  std::optional<llvm::APSInt> LHSValue =
15779 
15780  // We don't care about expressions whose result is a constant.
15781  if (RHSValue && LHSValue)
15782  return AnalyzeImpConvsInComparison(S, E);
15783 
15784  // We only care about expressions where just one side is literal
15785  if ((bool)RHSValue ^ (bool)LHSValue) {
15786  // Is the constant on the RHS or LHS?
15787  const bool RhsConstant = (bool)RHSValue;
15788  Expr *Const = RhsConstant ? RHS : LHS;
15789  Expr *Other = RhsConstant ? LHS : RHS;
15790  const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
15791 
15792  // Check whether an integer constant comparison results in a value
15793  // of 'true' or 'false'.
15794  if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
15795  return AnalyzeImpConvsInComparison(S, E);
15796  }
15797  }
15798 
15800  // We don't do anything special if this isn't an unsigned integral
15801  // comparison: we're only interested in integral comparisons, and
15802  // signed comparisons only happen in cases we don't care to warn about.
15803  return AnalyzeImpConvsInComparison(S, E);
15804  }
15805 
15806  LHS = LHS->IgnoreParenImpCasts();
15807  RHS = RHS->IgnoreParenImpCasts();
15808 
15809  if (!S.getLangOpts().CPlusPlus) {
15810  // Avoid warning about comparison of integers with different signs when
15811  // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
15812  // the type of `E`.
15813  if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
15814  LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
15815  if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
15816  RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
15817  }
15818 
15819  // Check to see if one of the (unmodified) operands is of different
15820  // signedness.
15821  Expr *signedOperand, *unsignedOperand;
15822  if (LHS->getType()->hasSignedIntegerRepresentation()) {
15823  assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
15824  "unsigned comparison between two signed integer expressions?");
15825  signedOperand = LHS;
15826  unsignedOperand = RHS;
15827  } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
15828  signedOperand = RHS;
15829  unsignedOperand = LHS;
15830  } else {
15831  return AnalyzeImpConvsInComparison(S, E);
15832  }
15833 
15834  // Otherwise, calculate the effective range of the signed operand.
15835  IntRange signedRange =
15836  GetExprRange(S.Context, signedOperand, S.isConstantEvaluatedContext(),
15837  /*Approximate=*/true);
15838 
15839  // Go ahead and analyze implicit conversions in the operands. Note
15840  // that we skip the implicit conversions on both sides.
15843 
15844  // If the signed range is non-negative, -Wsign-compare won't fire.
15845  if (signedRange.NonNegative)
15846  return;
15847 
15848  // For (in)equality comparisons, if the unsigned operand is a
15849  // constant which cannot collide with a overflowed signed operand,
15850  // then reinterpreting the signed operand as unsigned will not
15851  // change the result of the comparison.
15852  if (E->isEqualityOp()) {
15853  unsigned comparisonWidth = S.Context.getIntWidth(T);
15854  IntRange unsignedRange =
15855  GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
15856  /*Approximate=*/true);
15857 
15858  // We should never be unable to prove that the unsigned operand is
15859  // non-negative.
15860  assert(unsignedRange.NonNegative && "unsigned range includes negative?");
15861 
15862  if (unsignedRange.Width < comparisonWidth)
15863  return;
15864  }
15865 
15867  S.PDiag(diag::warn_mixed_sign_comparison)
15868  << LHS->getType() << RHS->getType()
15869  << LHS->getSourceRange() << RHS->getSourceRange());
15870 }
15871 
15872 /// Analyzes an attempt to assign the given value to a bitfield.
15873 ///
15874 /// Returns true if there was something fishy about the attempt.
15875 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
15876  SourceLocation InitLoc) {
15877  assert(Bitfield->isBitField());
15878  if (Bitfield->isInvalidDecl())
15879  return false;
15880 
15881  // White-list bool bitfields.
15882  QualType BitfieldType = Bitfield->getType();
15883  if (BitfieldType->isBooleanType())
15884  return false;
15885 
15886  if (BitfieldType->isEnumeralType()) {
15887  EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
15888  // If the underlying enum type was not explicitly specified as an unsigned
15889  // type and the enum contain only positive values, MSVC++ will cause an
15890  // inconsistency by storing this as a signed type.
15891  if (S.getLangOpts().CPlusPlus11 &&
15892  !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
15893  BitfieldEnumDecl->getNumPositiveBits() > 0 &&
15894  BitfieldEnumDecl->getNumNegativeBits() == 0) {
15895  S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
15896  << BitfieldEnumDecl;
15897  }
15898  }
15899 
15900  // Ignore value- or type-dependent expressions.
15901  if (Bitfield->getBitWidth()->isValueDependent() ||
15902  Bitfield->getBitWidth()->isTypeDependent() ||
15903  Init->isValueDependent() ||
15904  Init->isTypeDependent())
15905  return false;
15906 
15907  Expr *OriginalInit = Init->IgnoreParenImpCasts();
15908  unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
15909 
15910  Expr::EvalResult Result;
15911  if (!OriginalInit->EvaluateAsInt(Result, S.Context,
15913  // The RHS is not constant. If the RHS has an enum type, make sure the
15914  // bitfield is wide enough to hold all the values of the enum without
15915  // truncation.
15916  if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
15917  EnumDecl *ED = EnumTy->getDecl();
15918  bool SignedBitfield = BitfieldType->isSignedIntegerType();
15919 
15920  // Enum types are implicitly signed on Windows, so check if there are any
15921  // negative enumerators to see if the enum was intended to be signed or
15922  // not.
15923  bool SignedEnum = ED->getNumNegativeBits() > 0;
15924 
15925  // Check for surprising sign changes when assigning enum values to a
15926  // bitfield of different signedness. If the bitfield is signed and we
15927  // have exactly the right number of bits to store this unsigned enum,
15928  // suggest changing the enum to an unsigned type. This typically happens
15929  // on Windows where unfixed enums always use an underlying type of 'int'.
15930  unsigned DiagID = 0;
15931  if (SignedEnum && !SignedBitfield) {
15932  DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
15933  } else if (SignedBitfield && !SignedEnum &&
15934  ED->getNumPositiveBits() == FieldWidth) {
15935  DiagID = diag::warn_signed_bitfield_enum_conversion;
15936  }
15937 
15938  if (DiagID) {
15939  S.Diag(InitLoc, DiagID) << Bitfield << ED;
15940  TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
15941  SourceRange TypeRange =
15942  TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
15943  S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
15944  << SignedEnum << TypeRange;
15945  }
15946 
15947  // Compute the required bitwidth. If the enum has negative values, we need
15948  // one more bit than the normal number of positive bits to represent the
15949  // sign bit.
15950  unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
15951  ED->getNumNegativeBits())
15952  : ED->getNumPositiveBits();
15953 
15954  // Check the bitwidth.
15955  if (BitsNeeded > FieldWidth) {
15956  Expr *WidthExpr = Bitfield->getBitWidth();
15957  S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
15958  << Bitfield << ED;
15959  S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
15960  << BitsNeeded << ED << WidthExpr->getSourceRange();
15961  }
15962  }
15963 
15964  return false;
15965  }
15966 
15967  llvm::APSInt Value = Result.Val.getInt();
15968 
15969  unsigned OriginalWidth = Value.getBitWidth();
15970 
15971  // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
15972  // false positives where the user is demonstrating they intend to use the
15973  // bit-field as a Boolean, check to see if the value is 1 and we're assigning
15974  // to a one-bit bit-field to see if the value came from a macro named 'true'.
15975  bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
15976  if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
15977  SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
15978  if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
15979  S.findMacroSpelling(MaybeMacroLoc, "true"))
15980  return false;
15981  }
15982 
15983  if (!Value.isSigned() || Value.isNegative())
15984  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
15985  if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
15986  OriginalWidth = Value.getSignificantBits();
15987 
15988  if (OriginalWidth <= FieldWidth)
15989  return false;
15990 
15991  // Compute the value which the bitfield will contain.
15992  llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
15993  TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
15994 
15995  // Check whether the stored value is equal to the original value.
15996  TruncatedValue = TruncatedValue.extend(OriginalWidth);
15997  if (llvm::APSInt::isSameValue(Value, TruncatedValue))
15998  return false;
15999 
16000  std::string PrettyValue = toString(Value, 10);
16001  std::string PrettyTrunc = toString(TruncatedValue, 10);
16002 
16003  S.Diag(InitLoc, OneAssignedToOneBitBitfield
16004  ? diag::warn_impcast_single_bit_bitield_precision_constant
16005  : diag::warn_impcast_bitfield_precision_constant)
16006  << PrettyValue << PrettyTrunc << OriginalInit->getType()
16007  << Init->getSourceRange();
16008 
16009  return true;
16010 }
16011 
16012 /// Analyze the given simple or compound assignment for warning-worthy
16013 /// operations.
16015  // Just recurse on the LHS.
16017 
16018  // We want to recurse on the RHS as normal unless we're assigning to
16019  // a bitfield.
16020  if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
16021  if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
16022  E->getOperatorLoc())) {
16023  // Recurse, ignoring any implicit conversions on the RHS.
16025  E->getOperatorLoc());
16026  }
16027  }
16028 
16030 
16031  // Diagnose implicitly sequentially-consistent atomic assignment.
16032  if (E->getLHS()->getType()->isAtomicType())
16033  S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
16034 }
16035 
16036 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
16037 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
16038  SourceLocation CContext, unsigned diag,
16039  bool pruneControlFlow = false) {
16040  if (pruneControlFlow) {
16041  S.DiagRuntimeBehavior(E->getExprLoc(), E,
16042  S.PDiag(diag)
16043  << SourceType << T << E->getSourceRange()
16044  << SourceRange(CContext));
16045  return;
16046  }
16047  S.Diag(E->getExprLoc(), diag)
16048  << SourceType << T << E->getSourceRange() << SourceRange(CContext);
16049 }
16050 
16051 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
16052 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
16053  SourceLocation CContext,
16054  unsigned diag, bool pruneControlFlow = false) {
16055  DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
16056 }
16057 
16058 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
16059  return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
16060  S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
16061 }
16062 
16064  Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
16065  Expr *Ignored = SourceExpr->IgnoreImplicit();
16066  if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
16067  Ignored = OVE->getSourceExpr();
16068  bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
16069  isa<BinaryOperator>(Ignored) ||
16070  isa<CXXOperatorCallExpr>(Ignored);
16071  SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
16072  if (NeedsParens)
16073  Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
16074  << FixItHint::CreateInsertion(EndLoc, ")");
16075  Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
16076 }
16077 
16078 /// Diagnose an implicit cast from a floating point value to an integer value.
16080  SourceLocation CContext) {
16081  const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
16082  const bool PruneWarnings = S.inTemplateInstantiation();
16083 
16084  Expr *InnerE = E->IgnoreParenImpCasts();
16085  // We also want to warn on, e.g., "int i = -1.234"
16086  if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
16087  if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
16088  InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
16089 
16090  const bool IsLiteral =
16091  isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
16092 
16093  llvm::APFloat Value(0.0);
16094  bool IsConstant =
16096  if (!IsConstant) {
16097  if (isObjCSignedCharBool(S, T)) {
16099  S, E,
16100  S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
16101  << E->getType());
16102  }
16103 
16104  return DiagnoseImpCast(S, E, T, CContext,
16105  diag::warn_impcast_float_integer, PruneWarnings);
16106  }
16107 
16108  bool isExact = false;
16109 
16110  llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
16112  llvm::APFloat::opStatus Result = Value.convertToInteger(
16113  IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
16114 
16115  // FIXME: Force the precision of the source value down so we don't print
16116  // digits which are usually useless (we don't really care here if we
16117  // truncate a digit by accident in edge cases). Ideally, APFloat::toString
16118  // would automatically print the shortest representation, but it's a bit
16119  // tricky to implement.
16120  SmallString<16> PrettySourceValue;
16121  unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
16122  precision = (precision * 59 + 195) / 196;
16123  Value.toString(PrettySourceValue, precision);
16124 
16125  if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
16127  S, E,
16128  S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
16129  << PrettySourceValue);
16130  }
16131 
16132  if (Result == llvm::APFloat::opOK && isExact) {
16133  if (IsLiteral) return;
16134  return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
16135  PruneWarnings);
16136  }
16137 
16138  // Conversion of a floating-point value to a non-bool integer where the
16139  // integral part cannot be represented by the integer type is undefined.
16140  if (!IsBool && Result == llvm::APFloat::opInvalidOp)
16141  return DiagnoseImpCast(
16142  S, E, T, CContext,
16143  IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
16144  : diag::warn_impcast_float_to_integer_out_of_range,
16145  PruneWarnings);
16146 
16147  unsigned DiagID = 0;
16148  if (IsLiteral) {
16149  // Warn on floating point literal to integer.
16150  DiagID = diag::warn_impcast_literal_float_to_integer;
16151  } else if (IntegerValue == 0) {
16152  if (Value.isZero()) { // Skip -0.0 to 0 conversion.
16153  return DiagnoseImpCast(S, E, T, CContext,
16154  diag::warn_impcast_float_integer, PruneWarnings);
16155  }
16156  // Warn on non-zero to zero conversion.
16157  DiagID = diag::warn_impcast_float_to_integer_zero;
16158  } else {
16159  if (IntegerValue.isUnsigned()) {
16160  if (!IntegerValue.isMaxValue()) {
16161  return DiagnoseImpCast(S, E, T, CContext,
16162  diag::warn_impcast_float_integer, PruneWarnings);
16163  }
16164  } else { // IntegerValue.isSigned()
16165  if (!IntegerValue.isMaxSignedValue() &&
16166  !IntegerValue.isMinSignedValue()) {
16167  return DiagnoseImpCast(S, E, T, CContext,
16168  diag::warn_impcast_float_integer, PruneWarnings);
16169  }
16170  }
16171  // Warn on evaluatable floating point expression to integer conversion.
16172  DiagID = diag::warn_impcast_float_to_integer;
16173  }
16174 
16175  SmallString<16> PrettyTargetValue;
16176  if (IsBool)
16177  PrettyTargetValue = Value.isZero() ? "false" : "true";
16178  else
16179  IntegerValue.toString(PrettyTargetValue);
16180 
16181  if (PruneWarnings) {
16182  S.DiagRuntimeBehavior(E->getExprLoc(), E,
16183  S.PDiag(DiagID)
16184  << E->getType() << T.getUnqualifiedType()
16185  << PrettySourceValue << PrettyTargetValue
16186  << E->getSourceRange() << SourceRange(CContext));
16187  } else {
16188  S.Diag(E->getExprLoc(), DiagID)
16189  << E->getType() << T.getUnqualifiedType() << PrettySourceValue
16190  << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
16191  }
16192 }
16193 
16194 /// Analyze the given compound assignment for the possible losing of
16195 /// floating-point precision.
16197  assert(isa<CompoundAssignOperator>(E) &&
16198  "Must be compound assignment operation");
16199  // Recurse on the LHS and RHS in here
16202 
16203  if (E->getLHS()->getType()->isAtomicType())
16204  S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
16205 
16206  // Now check the outermost expression
16207  const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
16208  const auto *RBT = cast<CompoundAssignOperator>(E)
16209  ->getComputationResultType()
16210  ->getAs<BuiltinType>();
16211 
16212  // The below checks assume source is floating point.
16213  if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
16214 
16215  // If source is floating point but target is an integer.
16216  if (ResultBT->isInteger())
16217  return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
16218  E->getExprLoc(), diag::warn_impcast_float_integer);
16219 
16220  if (!ResultBT->isFloatingPoint())
16221  return;
16222 
16223  // If both source and target are floating points, warn about losing precision.
16225  QualType(ResultBT, 0), QualType(RBT, 0));
16226  if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
16227  // warn about dropping FP rank.
16228  DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
16229  diag::warn_impcast_float_result_precision);
16230 }
16231 
16232 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
16233  IntRange Range) {
16234  if (!Range.Width) return "0";
16235 
16236  llvm::APSInt ValueInRange = Value;
16237  ValueInRange.setIsSigned(!Range.NonNegative);
16238  ValueInRange = ValueInRange.trunc(Range.Width);
16239  return toString(ValueInRange, 10);
16240 }
16241 
16242 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
16243  if (!isa<ImplicitCastExpr>(Ex))
16244  return false;
16245 
16246  Expr *InnerE = Ex->IgnoreParenImpCasts();
16247  const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
16248  const Type *Source =
16249  S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
16250  if (Target->isDependentType())
16251  return false;
16252 
16253  const BuiltinType *FloatCandidateBT =
16254  dyn_cast<BuiltinType>(ToBool ? Source : Target);
16255  const Type *BoolCandidateType = ToBool ? Target : Source;
16256 
16257  return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
16258  FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
16259 }
16260 
16262  SourceLocation CC) {
16263  unsigned NumArgs = TheCall->getNumArgs();
16264  for (unsigned i = 0; i < NumArgs; ++i) {
16265  Expr *CurrA = TheCall->getArg(i);
16266  if (!IsImplicitBoolFloatConversion(S, CurrA, true))
16267  continue;
16268 
16269  bool IsSwapped = ((i > 0) &&
16270  IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
16271  IsSwapped |= ((i < (NumArgs - 1)) &&
16272  IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
16273  if (IsSwapped) {
16274  // Warn on this floating-point to bool conversion.
16276  CurrA->getType(), CC,
16277  diag::warn_impcast_floating_point_to_bool);
16278  }
16279  }
16280 }
16281 
16283  SourceLocation CC) {
16284  if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
16285  E->getExprLoc()))
16286  return;
16287 
16288  // Don't warn on functions which have return type nullptr_t.
16289  if (isa<CallExpr>(E))
16290  return;
16291 
16292  // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
16293  const Expr *NewE = E->IgnoreParenImpCasts();
16294  bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
16295  bool HasNullPtrType = NewE->getType()->isNullPtrType();
16296  if (!IsGNUNullExpr && !HasNullPtrType)
16297  return;
16298 
16299  // Return if target type is a safe conversion.
16300  if (T->isAnyPointerType() || T->isBlockPointerType() ||
16302  return;
16303 
16304  SourceLocation Loc = E->getSourceRange().getBegin();
16305 
16306  // Venture through the macro stacks to get to the source of macro arguments.
16307  // The new location is a better location than the complete location that was
16308  // passed in.
16309  Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
16310  CC = S.SourceMgr.getTopMacroCallerLoc(CC);
16311 
16312  // __null is usually wrapped in a macro. Go up a macro if that is the case.
16313  if (IsGNUNullExpr && Loc.isMacroID()) {
16314  StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
16315  Loc, S.SourceMgr, S.getLangOpts());
16316  if (MacroName == "NULL")
16318  }
16319 
16320  // Only warn if the null and context location are in the same macro expansion.
16321  if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
16322  return;
16323 
16324  S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
16325  << HasNullPtrType << T << SourceRange(CC)
16327  S.getFixItZeroLiteralForType(T, Loc));
16328 }
16329 
16330 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
16331  ObjCArrayLiteral *ArrayLiteral);
16332 
16333 static void
16335  ObjCDictionaryLiteral *DictionaryLiteral);
16336 
16337 /// Check a single element within a collection literal against the
16338 /// target element type.
16340  QualType TargetElementType,
16341  Expr *Element,
16342  unsigned ElementKind) {
16343  // Skip a bitcast to 'id' or qualified 'id'.
16344  if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
16345  if (ICE->getCastKind() == CK_BitCast &&
16346  ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
16347  Element = ICE->getSubExpr();
16348  }
16349 
16350  QualType ElementType = Element->getType();
16351  ExprResult ElementResult(Element);
16352  if (ElementType->getAs<ObjCObjectPointerType>() &&
16353  S.CheckSingleAssignmentConstraints(TargetElementType,
16354  ElementResult,
16355  false, false)
16356  != Sema::Compatible) {
16357  S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
16358  << ElementType << ElementKind << TargetElementType
16359  << Element->getSourceRange();
16360  }
16361 
16362  if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
16363  checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
16364  else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
16365  checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
16366 }
16367 
16368 /// Check an Objective-C array literal being converted to the given
16369 /// target type.
16370 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
16371  ObjCArrayLiteral *ArrayLiteral) {
16372  if (!S.NSArrayDecl)
16373  return;
16374 
16375  const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
16376  if (!TargetObjCPtr)
16377  return;
16378 
16379  if (TargetObjCPtr->isUnspecialized() ||
16380  TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
16381  != S.NSArrayDecl->getCanonicalDecl())
16382  return;
16383 
16384  auto TypeArgs = TargetObjCPtr->getTypeArgs();
16385  if (TypeArgs.size() != 1)
16386  return;
16387 
16388  QualType TargetElementType = TypeArgs[0];
16389  for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
16390  checkObjCCollectionLiteralElement(S, TargetElementType,
16391  ArrayLiteral->getElement(I),
16392  0);
16393  }
16394 }
16395 
16396 /// Check an Objective-C dictionary literal being converted to the given
16397 /// target type.
16398 static void
16400  ObjCDictionaryLiteral *DictionaryLiteral) {
16401  if (!S.NSDictionaryDecl)
16402  return;
16403 
16404  const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
16405  if (!TargetObjCPtr)
16406  return;
16407 
16408  if (TargetObjCPtr->isUnspecialized() ||
16409  TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
16411  return;
16412 
16413  auto TypeArgs = TargetObjCPtr->getTypeArgs();
16414  if (TypeArgs.size() != 2)
16415  return;
16416 
16417  QualType TargetKeyType = TypeArgs[0];
16418  QualType TargetObjectType = TypeArgs[1];
16419  for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
16420  auto Element = DictionaryLiteral->getKeyValueElement(I);
16421  checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
16422  checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
16423  }
16424 }
16425 
16426 // Helper function to filter out cases for constant width constant conversion.
16427 // Don't warn on char array initialization or for non-decimal values.
16429  SourceLocation CC) {
16430  // If initializing from a constant, and the constant starts with '0',
16431  // then it is a binary, octal, or hexadecimal. Allow these constants
16432  // to fill all the bits, even if there is a sign change.
16433  if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
16434  const char FirstLiteralCharacter =
16435  S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
16436  if (FirstLiteralCharacter == '0')
16437  return false;
16438  }
16439 
16440  // If the CC location points to a '{', and the type is char, then assume
16441  // assume it is an array initialization.
16442  if (CC.isValid() && T->isCharType()) {
16443  const char FirstContextCharacter =
16445  if (FirstContextCharacter == '{')
16446  return false;
16447  }
16448 
16449  return true;
16450 }
16451 
16453  const auto *IL = dyn_cast<IntegerLiteral>(E);
16454  if (!IL) {
16455  if (auto *UO = dyn_cast<UnaryOperator>(E)) {
16456  if (UO->getOpcode() == UO_Minus)
16457  return dyn_cast<IntegerLiteral>(UO->getSubExpr());
16458  }
16459  }
16460 
16461  return IL;
16462 }
16463 
16464 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
16465  E = E->IgnoreParenImpCasts();
16466  SourceLocation ExprLoc = E->getExprLoc();
16467 
16468  if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
16469  BinaryOperator::Opcode Opc = BO->getOpcode();
16470  Expr::EvalResult Result;
16471  // Do not diagnose unsigned shifts.
16472  if (Opc == BO_Shl) {
16473  const auto *LHS = getIntegerLiteral(BO->getLHS());
16474  const auto *RHS = getIntegerLiteral(BO->getRHS());
16475  if (LHS && LHS->getValue() == 0)
16476  S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
16477  else if (!E->isValueDependent() && LHS && RHS &&
16478  RHS->getValue().isNonNegative() &&
16480  S.Diag(ExprLoc, diag::warn_left_shift_always)
16481  << (Result.Val.getInt() != 0);
16482  else if (E->getType()->isSignedIntegerType())
16483  S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
16484  }
16485  }
16486 
16487  if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
16488  const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
16489  const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
16490  if (!LHS || !RHS)
16491  return;
16492  if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
16493  (RHS->getValue() == 0 || RHS->getValue() == 1))
16494  // Do not diagnose common idioms.
16495  return;
16496  if (LHS->getValue() != 0 && RHS->getValue() != 0)
16497  S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
16498  }
16499 }
16500 
16502  SourceLocation CC,
16503  bool *ICContext = nullptr,
16504  bool IsListInit = false) {
16505  if (E->isTypeDependent() || E->isValueDependent()) return;
16506 
16507  const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
16509  if (Source == Target) return;
16510  if (Target->isDependentType()) return;
16511 
16512  // If the conversion context location is invalid don't complain. We also
16513  // don't want to emit a warning if the issue occurs from the expansion of
16514  // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
16515  // delay this check as long as possible. Once we detect we are in that
16516  // scenario, we just return.
16517  if (CC.isInvalid())
16518  return;
16519 
16520  if (Source->isAtomicType())
16521  S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
16522 
16523  // Diagnose implicit casts to bool.
16524  if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
16525  if (isa<StringLiteral>(E))
16526  // Warn on string literal to bool. Checks for string literals in logical
16527  // and expressions, for instance, assert(0 && "error here"), are
16528  // prevented by a check in AnalyzeImplicitConversions().
16529  return DiagnoseImpCast(S, E, T, CC,
16530  diag::warn_impcast_string_literal_to_bool);
16531  if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
16532  isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
16533  // This covers the literal expressions that evaluate to Objective-C
16534  // objects.
16535  return DiagnoseImpCast(S, E, T, CC,
16536  diag::warn_impcast_objective_c_literal_to_bool);
16537  }
16538  if (Source->isPointerType() || Source->canDecayToPointerType()) {
16539  // Warn on pointer to bool conversion that is always true.
16540  S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
16541  SourceRange(CC));
16542  }
16543  }
16544 
16545  // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
16546  // is a typedef for signed char (macOS), then that constant value has to be 1
16547  // or 0.
16548  if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
16549  Expr::EvalResult Result;
16550  if (E->EvaluateAsInt(Result, S.getASTContext(),
16552  if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
16554  S, E,
16555  S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
16556  << toString(Result.Val.getInt(), 10));
16557  }
16558  return;
16559  }
16560  }
16561 
16562  // Check implicit casts from Objective-C collection literals to specialized
16563  // collection types, e.g., NSArray<NSString *> *.
16564  if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
16565  checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
16566  else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
16567  checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
16568 
16569  // Strip vector types.
16570  if (isa<VectorType>(Source)) {
16571  if (Target->isSveVLSBuiltinType() &&
16573  QualType(Source, 0)) ||
16575  QualType(Source, 0))))
16576  return;
16577 
16578  if (Target->isRVVVLSBuiltinType() &&
16580  QualType(Source, 0)) ||
16582  QualType(Source, 0))))
16583  return;
16584 
16585  if (!isa<VectorType>(Target)) {
16586  if (S.SourceMgr.isInSystemMacro(CC))
16587  return;
16588  return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
16589  } else if (S.getLangOpts().HLSL &&
16590  Target->castAs<VectorType>()->getNumElements() <
16591  Source->castAs<VectorType>()->getNumElements()) {
16592  // Diagnose vector truncation but don't return. We may also want to
16593  // diagnose an element conversion.
16594  DiagnoseImpCast(S, E, T, CC, diag::warn_hlsl_impcast_vector_truncation);
16595  }
16596 
16597  // If the vector cast is cast between two vectors of the same size, it is
16598  // a bitcast, not a conversion, except under HLSL where it is a conversion.
16599  if (!S.getLangOpts().HLSL &&
16600  S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
16601  return;
16602 
16603  Source = cast<VectorType>(Source)->getElementType().getTypePtr();
16604  Target = cast<VectorType>(Target)->getElementType().getTypePtr();
16605  }
16606  if (auto VecTy = dyn_cast<VectorType>(Target))
16607  Target = VecTy->getElementType().getTypePtr();
16608 
16609  // Strip complex types.
16610  if (isa<ComplexType>(Source)) {
16611  if (!isa<ComplexType>(Target)) {
16612  if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
16613  return;
16614 
16615  return DiagnoseImpCast(S, E, T, CC,
16616  S.getLangOpts().CPlusPlus
16617  ? diag::err_impcast_complex_scalar
16618  : diag::warn_impcast_complex_scalar);
16619  }
16620 
16621  Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
16622  Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
16623  }
16624 
16625  const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
16626  const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
16627 
16628  // Strip SVE vector types
16629  if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
16630  // Need the original target type for vector type checks
16631  const Type *OriginalTarget = S.Context.getCanonicalType(T).getTypePtr();
16632  // Handle conversion from scalable to fixed when msve-vector-bits is
16633  // specified
16634  if (S.Context.areCompatibleSveTypes(QualType(OriginalTarget, 0),
16635  QualType(Source, 0)) ||
16636  S.Context.areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
16637  QualType(Source, 0)))
16638  return;
16639 
16640  // If the vector cast is cast between two vectors of the same size, it is
16641  // a bitcast, not a conversion.
16642  if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
16643  return;
16644 
16645  Source = SourceBT->getSveEltType(S.Context).getTypePtr();
16646  }
16647 
16648  if (TargetBT && TargetBT->isSveVLSBuiltinType())
16649  Target = TargetBT->getSveEltType(S.Context).getTypePtr();
16650 
16651  // If the source is floating point...
16652  if (SourceBT && SourceBT->isFloatingPoint()) {
16653  // ...and the target is floating point...
16654  if (TargetBT && TargetBT->isFloatingPoint()) {
16655  // ...then warn if we're dropping FP rank.
16656 
16658  QualType(SourceBT, 0), QualType(TargetBT, 0));
16659  if (Order > 0) {
16660  // Don't warn about float constants that are precisely
16661  // representable in the target type.
16662  Expr::EvalResult result;
16663  if (E->EvaluateAsRValue(result, S.Context)) {
16664  // Value might be a float, a float vector, or a float complex.
16666  result.Val,
16667  S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
16668  S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) {
16669  if (S.getLangOpts().SYCLIsDevice)
16670  S.SYCL().DiagIfDeviceCode(CC,
16671  diag::warn_imp_float_size_conversion);
16672  else
16673  DiagnoseImpCast(S, E, T, CC,
16674  diag::warn_imp_float_size_conversion);
16675  return;
16676  }
16677  }
16678 
16679  if (S.SourceMgr.isInSystemMacro(CC))
16680  return;
16681  // If there is a precision conversion between floating point types when
16682  // -Wimplicit-float-size-conversion is passed but
16683  // -Wimplicit-float-conversion is not, make sure we emit at least a size
16684  // warning.
16685  if (S.Diags.isIgnored(diag::warn_impcast_float_precision, CC)) {
16686  if (S.getLangOpts().SYCLIsDevice)
16687  S.SYCL().DiagIfDeviceCode(CC, diag::warn_imp_float_size_conversion);
16688  else
16689  DiagnoseImpCast(S, E, T, CC, diag::warn_imp_float_size_conversion);
16690  }
16691  DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
16692  }
16693  // ... or possibly if we're increasing rank, too
16694  else if (Order < 0) {
16695  if (S.SourceMgr.isInSystemMacro(CC))
16696  return;
16697 
16698  DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
16699  }
16700  return;
16701  }
16702 
16703  // If the target is integral, always warn.
16704  if (TargetBT && TargetBT->isInteger()) {
16705  if (S.SourceMgr.isInSystemMacro(CC))
16706  return;
16707 
16708  DiagnoseFloatingImpCast(S, E, T, CC);
16709  }
16710 
16711  // Detect the case where a call result is converted from floating-point to
16712  // to bool, and the final argument to the call is converted from bool, to
16713  // discover this typo:
16714  //
16715  // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
16716  //
16717  // FIXME: This is an incredibly special case; is there some more general
16718  // way to detect this class of misplaced-parentheses bug?
16719  if (Target->isBooleanType() && isa<CallExpr>(E)) {
16720  // Check last argument of function call to see if it is an
16721  // implicit cast from a type matching the type the result
16722  // is being cast to.
16723  CallExpr *CEx = cast<CallExpr>(E);
16724  if (unsigned NumArgs = CEx->getNumArgs()) {
16725  Expr *LastA = CEx->getArg(NumArgs - 1);
16726  Expr *InnerE = LastA->IgnoreParenImpCasts();
16727  if (isa<ImplicitCastExpr>(LastA) &&
16728  InnerE->getType()->isBooleanType()) {
16729  // Warn on this floating-point to bool conversion
16730  DiagnoseImpCast(S, E, T, CC,
16731  diag::warn_impcast_floating_point_to_bool);
16732  }
16733  }
16734  }
16735  return;
16736  }
16737 
16738  // Valid casts involving fixed point types should be accounted for here.
16739  if (Source->isFixedPointType()) {
16740  if (Target->isUnsaturatedFixedPointType()) {
16741  Expr::EvalResult Result;
16744  llvm::APFixedPoint Value = Result.Val.getFixedPoint();
16745  llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
16746  llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
16747  if (Value > MaxVal || Value < MinVal) {
16748  S.DiagRuntimeBehavior(E->getExprLoc(), E,
16749  S.PDiag(diag::warn_impcast_fixed_point_range)
16750  << Value.toString() << T
16751  << E->getSourceRange()
16752  << clang::SourceRange(CC));
16753  return;
16754  }
16755  }
16756  } else if (Target->isIntegerType()) {
16757  Expr::EvalResult Result;
16758  if (!S.isConstantEvaluatedContext() &&
16759  E->EvaluateAsFixedPoint(Result, S.Context,
16761  llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
16762 
16763  bool Overflowed;
16764  llvm::APSInt IntResult = FXResult.convertToInt(
16765  S.Context.getIntWidth(T),
16766  Target->isSignedIntegerOrEnumerationType(), &Overflowed);
16767 
16768  if (Overflowed) {
16769  S.DiagRuntimeBehavior(E->getExprLoc(), E,
16770  S.PDiag(diag::warn_impcast_fixed_point_range)
16771  << FXResult.toString() << T
16772  << E->getSourceRange()
16773  << clang::SourceRange(CC));
16774  return;
16775  }
16776  }
16777  }
16778  } else if (Target->isUnsaturatedFixedPointType()) {
16779  if (Source->isIntegerType()) {
16780  Expr::EvalResult Result;
16781  if (!S.isConstantEvaluatedContext() &&
16783  llvm::APSInt Value = Result.Val.getInt();
16784 
16785  bool Overflowed;
16786  llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
16787  Value, S.Context.getFixedPointSemantics(T), &Overflowed);
16788 
16789  if (Overflowed) {
16790  S.DiagRuntimeBehavior(E->getExprLoc(), E,
16791  S.PDiag(diag::warn_impcast_fixed_point_range)
16792  << toString(Value, /*Radix=*/10) << T
16793  << E->getSourceRange()
16794  << clang::SourceRange(CC));
16795  return;
16796  }
16797  }
16798  }
16799  }
16800 
16801  // If we are casting an integer type to a floating point type without
16802  // initialization-list syntax, we might lose accuracy if the floating
16803  // point type has a narrower significand than the integer type.
16804  if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
16805  TargetBT->isFloatingType() && !IsListInit) {
16806  // Determine the number of precision bits in the source integer type.
16807  IntRange SourceRange =
16809  /*Approximate=*/true);
16810  unsigned int SourcePrecision = SourceRange.Width;
16811 
16812  // Determine the number of precision bits in the
16813  // target floating point type.
16814  unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
16815  S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
16816 
16817  if (SourcePrecision > 0 && TargetPrecision > 0 &&
16818  SourcePrecision > TargetPrecision) {
16819 
16820  if (std::optional<llvm::APSInt> SourceInt =
16822  // If the source integer is a constant, convert it to the target
16823  // floating point type. Issue a warning if the value changes
16824  // during the whole conversion.
16825  llvm::APFloat TargetFloatValue(
16826  S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
16827  llvm::APFloat::opStatus ConversionStatus =
16828  TargetFloatValue.convertFromAPInt(
16829  *SourceInt, SourceBT->isSignedInteger(),
16830  llvm::APFloat::rmNearestTiesToEven);
16831 
16832  if (ConversionStatus != llvm::APFloat::opOK) {
16833  SmallString<32> PrettySourceValue;
16834  SourceInt->toString(PrettySourceValue, 10);
16835  SmallString<32> PrettyTargetValue;
16836  TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
16837 
16839  E->getExprLoc(), E,
16840  S.PDiag(diag::warn_impcast_integer_float_precision_constant)
16841  << PrettySourceValue << PrettyTargetValue << E->getType() << T
16842  << E->getSourceRange() << clang::SourceRange(CC));
16843  }
16844  } else {
16845  // Otherwise, the implicit conversion may lose precision.
16846  DiagnoseImpCast(S, E, T, CC,
16847  diag::warn_impcast_integer_float_precision);
16848  }
16849  }
16850  }
16851 
16852  DiagnoseNullConversion(S, E, T, CC);
16853 
16855 
16856  if (Target->isBooleanType())
16858 
16859  if (!Source->isIntegerType() || !Target->isIntegerType())
16860  return;
16861 
16862  // TODO: remove this early return once the false positives for constant->bool
16863  // in templates, macros, etc, are reduced or removed.
16864  if (Target->isSpecificBuiltinType(BuiltinType::Bool))
16865  return;
16866 
16867  if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
16868  !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
16870  S, E,
16871  S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
16872  << E->getType());
16873  }
16874 
16875  IntRange SourceTypeRange =
16876  IntRange::forTargetOfCanonicalType(S.Context, Source);
16877  IntRange LikelySourceRange = GetExprRange(
16878  S.Context, E, S.isConstantEvaluatedContext(), /*Approximate=*/true);
16879  IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
16880 
16881  if (LikelySourceRange.Width > TargetRange.Width) {
16882  // If the source is a constant, use a default-on diagnostic.
16883  // TODO: this should happen for bitfield stores, too.
16884  Expr::EvalResult Result;
16887  llvm::APSInt Value(32);
16888  Value = Result.Val.getInt();
16889 
16890  if (S.SourceMgr.isInSystemMacro(CC))
16891  return;
16892 
16893  std::string PrettySourceValue = toString(Value, 10);
16894  std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
16895 
16897  E->getExprLoc(), E,
16898  S.PDiag(diag::warn_impcast_integer_precision_constant)
16899  << PrettySourceValue << PrettyTargetValue << E->getType() << T
16900  << E->getSourceRange() << SourceRange(CC));
16901  return;
16902  }
16903 
16904  // People want to build with -Wshorten-64-to-32 and not -Wconversion.
16905  if (S.SourceMgr.isInSystemMacro(CC))
16906  return;
16907 
16908  if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
16909  return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
16910  /* pruneControlFlow */ true);
16911  return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
16912  }
16913 
16914  if (TargetRange.Width > SourceTypeRange.Width) {
16915  if (auto *UO = dyn_cast<UnaryOperator>(E))
16916  if (UO->getOpcode() == UO_Minus)
16917  if (Source->isUnsignedIntegerType()) {
16918  if (Target->isUnsignedIntegerType())
16919  return DiagnoseImpCast(S, E, T, CC,
16920  diag::warn_impcast_high_order_zero_bits);
16921  if (Target->isSignedIntegerType())
16922  return DiagnoseImpCast(S, E, T, CC,
16923  diag::warn_impcast_nonnegative_result);
16924  }
16925  }
16926 
16927  if (TargetRange.Width == LikelySourceRange.Width &&
16928  !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
16929  Source->isSignedIntegerType()) {
16930  // Warn when doing a signed to signed conversion, warn if the positive
16931  // source value is exactly the width of the target type, which will
16932  // cause a negative value to be stored.
16933 
16934  Expr::EvalResult Result;
16935  if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
16936  !S.SourceMgr.isInSystemMacro(CC)) {
16937  llvm::APSInt Value = Result.Val.getInt();
16938  if (isSameWidthConstantConversion(S, E, T, CC)) {
16939  std::string PrettySourceValue = toString(Value, 10);
16940  std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
16941 
16943  E->getExprLoc(), E,
16944  S.PDiag(diag::warn_impcast_integer_precision_constant)
16945  << PrettySourceValue << PrettyTargetValue << E->getType() << T
16946  << E->getSourceRange() << SourceRange(CC));
16947  return;
16948  }
16949  }
16950 
16951  // Fall through for non-constants to give a sign conversion warning.
16952  }
16953 
16954  if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
16955  ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
16956  (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
16957  LikelySourceRange.Width == TargetRange.Width))) {
16958  if (S.SourceMgr.isInSystemMacro(CC))
16959  return;
16960 
16961  if (SourceBT && SourceBT->isInteger() && TargetBT &&
16962  TargetBT->isInteger() &&
16963  Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
16964  return;
16965  }
16966 
16967  unsigned DiagID = diag::warn_impcast_integer_sign;
16968 
16969  // Traditionally, gcc has warned about this under -Wsign-compare.
16970  // We also want to warn about it in -Wconversion.
16971  // So if -Wconversion is off, use a completely identical diagnostic
16972  // in the sign-compare group.
16973  // The conditional-checking code will
16974  if (ICContext) {
16975  DiagID = diag::warn_impcast_integer_sign_conditional;
16976  *ICContext = true;
16977  }
16978 
16979  return DiagnoseImpCast(S, E, T, CC, DiagID);
16980  }
16981 
16982  // Diagnose conversions between different enumeration types.
16983  // In C, we pretend that the type of an EnumConstantDecl is its enumeration
16984  // type, to give us better diagnostics.
16985  QualType SourceType = E->getEnumCoercedType(S.Context);
16986  Source = S.Context.getCanonicalType(SourceType).getTypePtr();
16987 
16988  if (const EnumType *SourceEnum = Source->getAs<EnumType>())
16989  if (const EnumType *TargetEnum = Target->getAs<EnumType>())
16990  if (SourceEnum->getDecl()->hasNameForLinkage() &&
16991  TargetEnum->getDecl()->hasNameForLinkage() &&
16992  SourceEnum != TargetEnum) {
16993  if (S.SourceMgr.isInSystemMacro(CC))
16994  return;
16995 
16996  return DiagnoseImpCast(S, E, SourceType, T, CC,
16997  diag::warn_impcast_different_enum_types);
16998  }
16999 }
17000 
17002  SourceLocation CC, QualType T);
17003 
17005  SourceLocation CC, bool &ICContext) {
17006  E = E->IgnoreParenImpCasts();
17007  // Diagnose incomplete type for second or third operand in C.
17008  if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
17009  S.RequireCompleteExprType(E, diag::err_incomplete_type);
17010 
17011  if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
17012  return CheckConditionalOperator(S, CO, CC, T);
17013 
17014  AnalyzeImplicitConversions(S, E, CC);
17015  if (E->getType() != T)
17016  return CheckImplicitConversion(S, E, T, CC, &ICContext);
17017 }
17018 
17020  SourceLocation CC, QualType T) {
17022 
17023  Expr *TrueExpr = E->getTrueExpr();
17024  if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
17025  TrueExpr = BCO->getCommon();
17026 
17027  bool Suspicious = false;
17028  CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
17029  CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
17030 
17031  if (T->isBooleanType())
17033 
17034  // If -Wconversion would have warned about either of the candidates
17035  // for a signedness conversion to the context type...
17036  if (!Suspicious) return;
17037 
17038  // ...but it's currently ignored...
17039  if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
17040  return;
17041 
17042  // ...then check whether it would have warned about either of the
17043  // candidates for a signedness conversion to the condition type.
17044  if (E->getType() == T) return;
17045 
17046  Suspicious = false;
17048  E->getType(), CC, &Suspicious);
17049  if (!Suspicious)
17051  E->getType(), CC, &Suspicious);
17052 }
17053 
17054 /// Check conversion of given expression to boolean.
17055 /// Input argument E is a logical expression.
17057  // Run the bool-like conversion checks only for C since there bools are
17058  // still not used as the return type from "boolean" operators or as the input
17059  // type for conditional operators.
17060  if (S.getLangOpts().CPlusPlus)
17061  return;
17062  if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
17063  return;
17065 }
17066 
17067 namespace {
17068 struct AnalyzeImplicitConversionsWorkItem {
17069  Expr *E;
17070  SourceLocation CC;
17071  bool IsListInit;
17072 };
17073 }
17074 
17075 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
17076 /// that should be visited are added to WorkList.
17078  Sema &S, AnalyzeImplicitConversionsWorkItem Item,
17080  Expr *OrigE = Item.E;
17081  SourceLocation CC = Item.CC;
17082 
17083  QualType T = OrigE->getType();
17084  Expr *E = OrigE->IgnoreParenImpCasts();
17085 
17086  // Propagate whether we are in a C++ list initialization expression.
17087  // If so, we do not issue warnings for implicit int-float conversion
17088  // precision loss, because C++11 narrowing already handles it.
17089  bool IsListInit = Item.IsListInit ||
17090  (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
17091 
17092  if (E->isTypeDependent() || E->isValueDependent())
17093  return;
17094 
17095  Expr *SourceExpr = E;
17096  // Examine, but don't traverse into the source expression of an
17097  // OpaqueValueExpr, since it may have multiple parents and we don't want to
17098  // emit duplicate diagnostics. Its fine to examine the form or attempt to
17099  // evaluate it in the context of checking the specific conversion to T though.
17100  if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
17101  if (auto *Src = OVE->getSourceExpr())
17102  SourceExpr = Src;
17103 
17104  if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
17105  if (UO->getOpcode() == UO_Not &&
17106  UO->getSubExpr()->isKnownToHaveBooleanValue())
17107  S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
17108  << OrigE->getSourceRange() << T->isBooleanType()
17109  << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
17110 
17111  if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
17112  if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
17113  BO->getLHS()->isKnownToHaveBooleanValue() &&
17114  BO->getRHS()->isKnownToHaveBooleanValue() &&
17115  BO->getLHS()->HasSideEffects(S.Context) &&
17116  BO->getRHS()->HasSideEffects(S.Context)) {
17118  const LangOptions &LO = S.getLangOpts();
17119  SourceLocation BLoc = BO->getOperatorLoc();
17120  SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
17121  StringRef SR = clang::Lexer::getSourceText(
17122  clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
17123  // To reduce false positives, only issue the diagnostic if the operator
17124  // is explicitly spelled as a punctuator. This suppresses the diagnostic
17125  // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
17126  // in C, along with other macro spellings the user might invent.
17127  if (SR.str() == "&" || SR.str() == "|") {
17128 
17129  S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
17130  << (BO->getOpcode() == BO_And ? "&" : "|")
17131  << OrigE->getSourceRange()
17133  BO->getOperatorLoc(),
17134  (BO->getOpcode() == BO_And ? "&&" : "||"));
17135  S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
17136  }
17137  }
17138 
17139  // For conditional operators, we analyze the arguments as if they
17140  // were being fed directly into the output.
17141  if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
17142  CheckConditionalOperator(S, CO, CC, T);
17143  return;
17144  }
17145 
17146  // Check implicit argument conversions for function calls.
17147  if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
17148  CheckImplicitArgumentConversions(S, Call, CC);
17149 
17150  // Go ahead and check any implicit conversions we might have skipped.
17151  // The non-canonical typecheck is just an optimization;
17152  // CheckImplicitConversion will filter out dead implicit conversions.
17153  if (SourceExpr->getType() != T)
17154  CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
17155 
17156  // Now continue drilling into this expression.
17157 
17158  if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
17159  // The bound subexpressions in a PseudoObjectExpr are not reachable
17160  // as transitive children.
17161  // FIXME: Use a more uniform representation for this.
17162  for (auto *SE : POE->semantics())
17163  if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
17164  WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
17165  }
17166 
17167  // Skip past explicit casts.
17168  if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
17169  E = CE->getSubExpr()->IgnoreParenImpCasts();
17170  if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
17171  S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
17172  WorkList.push_back({E, CC, IsListInit});
17173  return;
17174  }
17175 
17176  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
17177  // Do a somewhat different check with comparison operators.
17178  if (BO->isComparisonOp())
17179  return AnalyzeComparison(S, BO);
17180 
17181  // And with simple assignments.
17182  if (BO->getOpcode() == BO_Assign)
17183  return AnalyzeAssignment(S, BO);
17184  // And with compound assignments.
17185  if (BO->isAssignmentOp())
17186  return AnalyzeCompoundAssignment(S, BO);
17187  }
17188 
17189  // These break the otherwise-useful invariant below. Fortunately,
17190  // we don't really need to recurse into them, because any internal
17191  // expressions should have been analyzed already when they were
17192  // built into statements.
17193  if (isa<StmtExpr>(E)) return;
17194 
17195  // Don't descend into unevaluated contexts.
17196  if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
17197 
17198  // Now just recurse over the expression's children.
17199  CC = E->getExprLoc();
17200  BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
17201  bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
17202  for (Stmt *SubStmt : E->children()) {
17203  Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
17204  if (!ChildExpr)
17205  continue;
17206 
17207  if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
17208  if (ChildExpr == CSE->getOperand())
17209  // Do not recurse over a CoroutineSuspendExpr's operand.
17210  // The operand is also a subexpression of getCommonExpr(), and
17211  // recursing into it directly would produce duplicate diagnostics.
17212  continue;
17213 
17214  if (IsLogicalAndOperator &&
17215  isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
17216  // Ignore checking string literals that are in logical and operators.
17217  // This is a common pattern for asserts.
17218  continue;
17219  WorkList.push_back({ChildExpr, CC, IsListInit});
17220  }
17221 
17222  if (BO && BO->isLogicalOp()) {
17223  Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
17224  if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
17225  ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
17226 
17227  SubExpr = BO->getRHS()->IgnoreParenImpCasts();
17228  if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
17229  ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
17230  }
17231 
17232  if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
17233  if (U->getOpcode() == UO_LNot) {
17234  ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
17235  } else if (U->getOpcode() != UO_AddrOf) {
17236  if (U->getSubExpr()->getType()->isAtomicType())
17237  S.Diag(U->getSubExpr()->getBeginLoc(),
17238  diag::warn_atomic_implicit_seq_cst);
17239  }
17240  }
17241 }
17242 
17243 /// AnalyzeImplicitConversions - Find and report any interesting
17244 /// implicit conversions in the given expression. There are a couple
17245 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
17247  bool IsListInit/*= false*/) {
17249  WorkList.push_back({OrigE, CC, IsListInit});
17250  while (!WorkList.empty())
17251  AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
17252 }
17253 
17254 /// Diagnose integer type and any valid implicit conversion to it.
17255 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
17256  // Taking into account implicit conversions,
17257  // allow any integer.
17258  if (!E->getType()->isIntegerType()) {
17259  S.Diag(E->getBeginLoc(),
17260  diag::err_opencl_enqueue_kernel_invalid_local_size_type);
17261  return true;
17262  }
17263  // Potentially emit standard warnings for implicit conversions if enabled
17264  // using -Wconversion.
17265  CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
17266  return false;
17267 }
17268 
17269 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
17270 // Returns true when emitting a warning about taking the address of a reference.
17271 static bool CheckForReference(Sema &SemaRef, const Expr *E,
17272  const PartialDiagnostic &PD) {
17273  E = E->IgnoreParenImpCasts();
17274 
17275  const FunctionDecl *FD = nullptr;
17276 
17277  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
17278  if (!DRE->getDecl()->getType()->isReferenceType())
17279  return false;
17280  } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
17281  if (!M->getMemberDecl()->getType()->isReferenceType())
17282  return false;
17283  } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
17284  if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
17285  return false;
17286  FD = Call->getDirectCallee();
17287  } else {
17288  return false;
17289  }
17290 
17291  SemaRef.Diag(E->getExprLoc(), PD);
17292 
17293  // If possible, point to location of function.
17294  if (FD) {
17295  SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
17296  }
17297 
17298  return true;
17299 }
17300 
17301 // Returns true if the SourceLocation is expanded from any macro body.
17302 // Returns false if the SourceLocation is invalid, is from not in a macro
17303 // expansion, or is from expanded from a top-level macro argument.
17305  if (Loc.isInvalid())
17306  return false;
17307 
17308  while (Loc.isMacroID()) {
17309  if (SM.isMacroBodyExpansion(Loc))
17310  return true;
17311  Loc = SM.getImmediateMacroCallerLoc(Loc);
17312  }
17313 
17314  return false;
17315 }
17316 
17317 /// Diagnose pointers that are always non-null.
17318 /// \param E the expression containing the pointer
17319 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
17320 /// compared to a null pointer
17321 /// \param IsEqual True when the comparison is equal to a null pointer
17322 /// \param Range Extra SourceRange to highlight in the diagnostic
17325  bool IsEqual, SourceRange Range) {
17326  if (!E)
17327  return;
17328 
17329  // Don't warn inside macros.
17330  if (E->getExprLoc().isMacroID()) {
17331  const SourceManager &SM = getSourceManager();
17332  if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
17333  IsInAnyMacroBody(SM, Range.getBegin()))
17334  return;
17335  }
17336  E = E->IgnoreImpCasts();
17337 
17338  const bool IsCompare = NullKind != Expr::NPCK_NotNull;
17339 
17340  if (isa<CXXThisExpr>(E)) {
17341  unsigned DiagID = IsCompare ? diag::warn_this_null_compare
17342  : diag::warn_this_bool_conversion;
17343  Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
17344  return;
17345  }
17346 
17347  bool IsAddressOf = false;
17348 
17349  if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
17350  if (UO->getOpcode() != UO_AddrOf)
17351  return;
17352  IsAddressOf = true;
17353  E = UO->getSubExpr();
17354  }
17355 
17356  if (IsAddressOf) {
17357  unsigned DiagID = IsCompare
17358  ? diag::warn_address_of_reference_null_compare
17359  : diag::warn_address_of_reference_bool_conversion;
17360  PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
17361  << IsEqual;
17362  if (CheckForReference(*this, E, PD)) {
17363  return;
17364  }
17365  }
17366 
17367  auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
17368  bool IsParam = isa<NonNullAttr>(NonnullAttr);
17369  std::string Str;
17370  llvm::raw_string_ostream S(Str);
17371  E->printPretty(S, nullptr, getPrintingPolicy());
17372  unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
17373  : diag::warn_cast_nonnull_to_bool;
17374  Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
17375  << E->getSourceRange() << Range << IsEqual;
17376  Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
17377  };
17378 
17379  // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
17380  if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
17381  if (auto *Callee = Call->getDirectCallee()) {
17382  if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
17383  ComplainAboutNonnullParamOrCall(A);
17384  return;
17385  }
17386  }
17387  }
17388 
17389  // Complain if we are converting a lambda expression to a boolean value
17390  // outside of instantiation.
17391  if (!inTemplateInstantiation()) {
17392  if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
17393  if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
17394  MRecordDecl && MRecordDecl->isLambda()) {
17395  Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
17396  << /*LambdaPointerConversionOperatorType=*/3
17397  << MRecordDecl->getSourceRange() << Range << IsEqual;
17398  return;
17399  }
17400  }
17401  }
17402 
17403  // Expect to find a single Decl. Skip anything more complicated.
17404  ValueDecl *D = nullptr;
17405  if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
17406  D = R->getDecl();
17407  } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
17408  D = M->getMemberDecl();
17409  }
17410 
17411  // Weak Decls can be null.
17412  if (!D || D->isWeak())
17413  return;
17414 
17415  // Check for parameter decl with nonnull attribute
17416  if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
17417  if (getCurFunction() &&
17418  !getCurFunction()->ModifiedNonNullParams.count(PV)) {
17419  if (const Attr *A = PV->getAttr<NonNullAttr>()) {
17420  ComplainAboutNonnullParamOrCall(A);
17421  return;
17422  }
17423 
17424  if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
17425  // Skip function template not specialized yet.
17427  return;
17428  auto ParamIter = llvm::find(FD->parameters(), PV);
17429  assert(ParamIter != FD->param_end());
17430  unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
17431 
17432  for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
17433  if (!NonNull->args_size()) {
17434  ComplainAboutNonnullParamOrCall(NonNull);
17435  return;
17436  }
17437 
17438  for (const ParamIdx &ArgNo : NonNull->args()) {
17439  if (ArgNo.getASTIndex() == ParamNo) {
17440  ComplainAboutNonnullParamOrCall(NonNull);
17441  return;
17442  }
17443  }
17444  }
17445  }
17446  }
17447  }
17448 
17449  QualType T = D->getType();
17450  const bool IsArray = T->isArrayType();
17451  const bool IsFunction = T->isFunctionType();
17452 
17453  // Address of function is used to silence the function warning.
17454  if (IsAddressOf && IsFunction) {
17455  return;
17456  }
17457 
17458  // Found nothing.
17459  if (!IsAddressOf && !IsFunction && !IsArray)
17460  return;
17461 
17462  // Pretty print the expression for the diagnostic.
17463  std::string Str;
17464  llvm::raw_string_ostream S(Str);
17465  E->printPretty(S, nullptr, getPrintingPolicy());
17466 
17467  unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
17468  : diag::warn_impcast_pointer_to_bool;
17469  enum {
17470  AddressOf,
17471  FunctionPointer,
17472  ArrayPointer
17473  } DiagType;
17474  if (IsAddressOf)
17475  DiagType = AddressOf;
17476  else if (IsFunction)
17477  DiagType = FunctionPointer;
17478  else if (IsArray)
17479  DiagType = ArrayPointer;
17480  else
17481  llvm_unreachable("Could not determine diagnostic.");
17482  Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
17483  << Range << IsEqual;
17484 
17485  if (!IsFunction)
17486  return;
17487 
17488  // Suggest '&' to silence the function warning.
17489  Diag(E->getExprLoc(), diag::note_function_warning_silence)
17491 
17492  // Check to see if '()' fixit should be emitted.
17493  QualType ReturnType;
17494  UnresolvedSet<4> NonTemplateOverloads;
17495  tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
17496  if (ReturnType.isNull())
17497  return;
17498 
17499  if (IsCompare) {
17500  // There are two cases here. If there is null constant, the only suggest
17501  // for a pointer return type. If the null is 0, then suggest if the return
17502  // type is a pointer or an integer type.
17503  if (!ReturnType->isPointerType()) {
17504  if (NullKind == Expr::NPCK_ZeroExpression ||
17505  NullKind == Expr::NPCK_ZeroLiteral) {
17506  if (!ReturnType->isIntegerType())
17507  return;
17508  } else {
17509  return;
17510  }
17511  }
17512  } else { // !IsCompare
17513  // For function to bool, only suggest if the function pointer has bool
17514  // return type.
17515  if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
17516  return;
17517  }
17518  Diag(E->getExprLoc(), diag::note_function_to_function_call)
17519  << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
17520 }
17521 
17522 /// Diagnoses "dangerous" implicit conversions within the given
17523 /// expression (which is a full expression). Implements -Wconversion
17524 /// and -Wsign-compare.
17525 ///
17526 /// \param CC the "context" location of the implicit conversion, i.e.
17527 /// the most location of the syntactic entity requiring the implicit
17528 /// conversion
17529 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
17530  // Don't diagnose in unevaluated contexts.
17531  if (isUnevaluatedContext())
17532  return;
17533 
17534  // Don't diagnose for value- or type-dependent expressions.
17535  if (E->isTypeDependent() || E->isValueDependent())
17536  return;
17537 
17538  // Check for array bounds violations in cases where the check isn't triggered
17539  // elsewhere for other Expr types (like BinaryOperators), e.g. when an
17540  // ArraySubscriptExpr is on the RHS of a variable initialization.
17541  CheckArrayAccess(E);
17542 
17543  // This is not the right CC for (e.g.) a variable initialization.
17544  AnalyzeImplicitConversions(*this, E, CC);
17545 }
17546 
17547 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
17548 /// Input argument E is a logical expression.
17549 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
17550  ::CheckBoolLikeConversion(*this, E, CC);
17551 }
17552 
17553 /// Diagnose when expression is an integer constant expression and its evaluation
17554 /// results in integer overflow
17555 void Sema::CheckForIntOverflow (const Expr *E) {
17556  // Use a work list to deal with nested struct initializers.
17557  SmallVector<const Expr *, 2> Exprs(1, E);
17558 
17559  do {
17560  const Expr *OriginalE = Exprs.pop_back_val();
17561  const Expr *E = OriginalE->IgnoreParenCasts();
17562 
17563  if (isa<BinaryOperator, UnaryOperator>(E)) {
17564  E->EvaluateForOverflow(Context);
17565  continue;
17566  }
17567 
17568  if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
17569  Exprs.append(InitList->inits().begin(), InitList->inits().end());
17570  else if (isa<ObjCBoxedExpr>(OriginalE))
17571  E->EvaluateForOverflow(Context);
17572  else if (const auto *Call = dyn_cast<CallExpr>(E))
17573  Exprs.append(Call->arg_begin(), Call->arg_end());
17574  else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
17575  Exprs.append(Message->arg_begin(), Message->arg_end());
17576  else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
17577  Exprs.append(Construct->arg_begin(), Construct->arg_end());
17578  else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
17579  Exprs.push_back(Temporary->getSubExpr());
17580  else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
17581  Exprs.push_back(Array->getIdx());
17582  else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
17583  Exprs.push_back(Compound->getInitializer());
17584  else if (const auto *New = dyn_cast<CXXNewExpr>(E);
17585  New && New->isArray()) {
17586  if (auto ArraySize = New->getArraySize())
17587  Exprs.push_back(*ArraySize);
17588  }
17589  } while (!Exprs.empty());
17590 }
17591 
17592 namespace {
17593 
17594 /// Visitor for expressions which looks for unsequenced operations on the
17595 /// same object.
17596 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
17598 
17599  /// A tree of sequenced regions within an expression. Two regions are
17600  /// unsequenced if one is an ancestor or a descendent of the other. When we
17601  /// finish processing an expression with sequencing, such as a comma
17602  /// expression, we fold its tree nodes into its parent, since they are
17603  /// unsequenced with respect to nodes we will visit later.
17604  class SequenceTree {
17605  struct Value {
17606  explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
17607  unsigned Parent : 31;
17608  LLVM_PREFERRED_TYPE(bool)
17609  unsigned Merged : 1;
17610  };
17611  SmallVector<Value, 8> Values;
17612 
17613  public:
17614  /// A region within an expression which may be sequenced with respect
17615  /// to some other region.
17616  class Seq {
17617  friend class SequenceTree;
17618 
17619  unsigned Index;
17620 
17621  explicit Seq(unsigned N) : Index(N) {}
17622 
17623  public:
17624  Seq() : Index(0) {}
17625  };
17626 
17627  SequenceTree() { Values.push_back(Value(0)); }
17628  Seq root() const { return Seq(0); }
17629 
17630  /// Create a new sequence of operations, which is an unsequenced
17631  /// subset of \p Parent. This sequence of operations is sequenced with
17632  /// respect to other children of \p Parent.
17633  Seq allocate(Seq Parent) {
17634  Values.push_back(Value(Parent.Index));
17635  return Seq(Values.size() - 1);
17636  }
17637 
17638  /// Merge a sequence of operations into its parent.
17639  void merge(Seq S) {
17640  Values[S.Index].Merged = true;
17641  }
17642 
17643  /// Determine whether two operations are unsequenced. This operation
17644  /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
17645  /// should have been merged into its parent as appropriate.
17646  bool isUnsequenced(Seq Cur, Seq Old) {
17647  unsigned C = representative(Cur.Index);
17648  unsigned Target = representative(Old.Index);
17649  while (C >= Target) {
17650  if (C == Target)
17651  return true;
17652  C = Values[C].Parent;
17653  }
17654  return false;
17655  }
17656 
17657  private:
17658  /// Pick a representative for a sequence.
17659  unsigned representative(unsigned K) {
17660  if (Values[K].Merged)
17661  // Perform path compression as we go.
17662  return Values[K].Parent = representative(Values[K].Parent);
17663  return K;
17664  }
17665  };
17666 
17667  /// An object for which we can track unsequenced uses.
17668  using Object = const NamedDecl *;
17669 
17670  /// Different flavors of object usage which we track. We only track the
17671  /// least-sequenced usage of each kind.
17672  enum UsageKind {
17673  /// A read of an object. Multiple unsequenced reads are OK.
17674  UK_Use,
17675 
17676  /// A modification of an object which is sequenced before the value
17677  /// computation of the expression, such as ++n in C++.
17678  UK_ModAsValue,
17679 
17680  /// A modification of an object which is not sequenced before the value
17681  /// computation of the expression, such as n++.
17682  UK_ModAsSideEffect,
17683 
17684  UK_Count = UK_ModAsSideEffect + 1
17685  };
17686 
17687  /// Bundle together a sequencing region and the expression corresponding
17688  /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
17689  struct Usage {
17690  const Expr *UsageExpr = nullptr;
17691  SequenceTree::Seq Seq;
17692 
17693  Usage() = default;
17694  };
17695 
17696  struct UsageInfo {
17697  Usage Uses[UK_Count];
17698 
17699  /// Have we issued a diagnostic for this object already?
17700  bool Diagnosed = false;
17701 
17702  UsageInfo();
17703  };
17704  using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
17705 
17706  Sema &SemaRef;
17707 
17708  /// Sequenced regions within the expression.
17709  SequenceTree Tree;
17710 
17711  /// Declaration modifications and references which we have seen.
17712  UsageInfoMap UsageMap;
17713 
17714  /// The region we are currently within.
17715  SequenceTree::Seq Region;
17716 
17717  /// Filled in with declarations which were modified as a side-effect
17718  /// (that is, post-increment operations).
17719  SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
17720 
17721  /// Expressions to check later. We defer checking these to reduce
17722  /// stack usage.
17724 
17725  /// RAII object wrapping the visitation of a sequenced subexpression of an
17726  /// expression. At the end of this process, the side-effects of the evaluation
17727  /// become sequenced with respect to the value computation of the result, so
17728  /// we downgrade any UK_ModAsSideEffect within the evaluation to
17729  /// UK_ModAsValue.
17730  struct SequencedSubexpression {
17731  SequencedSubexpression(SequenceChecker &Self)
17732  : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
17733  Self.ModAsSideEffect = &ModAsSideEffect;
17734  }
17735 
17736  ~SequencedSubexpression() {
17737  for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
17738  // Add a new usage with usage kind UK_ModAsValue, and then restore
17739  // the previous usage with UK_ModAsSideEffect (thus clearing it if
17740  // the previous one was empty).
17741  UsageInfo &UI = Self.UsageMap[M.first];
17742  auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
17743  Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
17744  SideEffectUsage = M.second;
17745  }
17746  Self.ModAsSideEffect = OldModAsSideEffect;
17747  }
17748 
17749  SequenceChecker &Self;
17750  SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
17751  SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
17752  };
17753 
17754  /// RAII object wrapping the visitation of a subexpression which we might
17755  /// choose to evaluate as a constant. If any subexpression is evaluated and
17756  /// found to be non-constant, this allows us to suppress the evaluation of
17757  /// the outer expression.
17758  class EvaluationTracker {
17759  public:
17760  EvaluationTracker(SequenceChecker &Self)
17761  : Self(Self), Prev(Self.EvalTracker) {
17762  Self.EvalTracker = this;
17763  }
17764 
17765  ~EvaluationTracker() {
17766  Self.EvalTracker = Prev;
17767  if (Prev)
17768  Prev->EvalOK &= EvalOK;
17769  }
17770 
17771  bool evaluate(const Expr *E, bool &Result) {
17772  if (!EvalOK || E->isValueDependent())
17773  return false;
17774  EvalOK = E->EvaluateAsBooleanCondition(
17775  Result, Self.SemaRef.Context,
17776  Self.SemaRef.isConstantEvaluatedContext());
17777  return EvalOK;
17778  }
17779 
17780  private:
17781  SequenceChecker &Self;
17782  EvaluationTracker *Prev;
17783  bool EvalOK = true;
17784  } *EvalTracker = nullptr;
17785 
17786  /// Find the object which is produced by the specified expression,
17787  /// if any.
17788  Object getObject(const Expr *E, bool Mod) const {
17789  E = E->IgnoreParenCasts();
17790  if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
17791  if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
17792  return getObject(UO->getSubExpr(), Mod);
17793  } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
17794  if (BO->getOpcode() == BO_Comma)
17795  return getObject(BO->getRHS(), Mod);
17796  if (Mod && BO->isAssignmentOp())
17797  return getObject(BO->getLHS(), Mod);
17798  } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
17799  // FIXME: Check for more interesting cases, like "x.n = ++x.n".
17800  if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
17801  return ME->getMemberDecl();
17802  } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
17803  // FIXME: If this is a reference, map through to its value.
17804  return DRE->getDecl();
17805  return nullptr;
17806  }
17807 
17808  /// Note that an object \p O was modified or used by an expression
17809  /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
17810  /// the object \p O as obtained via the \p UsageMap.
17811  void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
17812  // Get the old usage for the given object and usage kind.
17813  Usage &U = UI.Uses[UK];
17814  if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
17815  // If we have a modification as side effect and are in a sequenced
17816  // subexpression, save the old Usage so that we can restore it later
17817  // in SequencedSubexpression::~SequencedSubexpression.
17818  if (UK == UK_ModAsSideEffect && ModAsSideEffect)
17819  ModAsSideEffect->push_back(std::make_pair(O, U));
17820  // Then record the new usage with the current sequencing region.
17821  U.UsageExpr = UsageExpr;
17822  U.Seq = Region;
17823  }
17824  }
17825 
17826  /// Check whether a modification or use of an object \p O in an expression
17827  /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
17828  /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
17829  /// \p IsModMod is true when we are checking for a mod-mod unsequenced
17830  /// usage and false we are checking for a mod-use unsequenced usage.
17831  void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
17832  UsageKind OtherKind, bool IsModMod) {
17833  if (UI.Diagnosed)
17834  return;
17835 
17836  const Usage &U = UI.Uses[OtherKind];
17837  if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
17838  return;
17839 
17840  const Expr *Mod = U.UsageExpr;
17841  const Expr *ModOrUse = UsageExpr;
17842  if (OtherKind == UK_Use)
17843  std::swap(Mod, ModOrUse);
17844 
17845  SemaRef.DiagRuntimeBehavior(
17846  Mod->getExprLoc(), {Mod, ModOrUse},
17847  SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
17848  : diag::warn_unsequenced_mod_use)
17849  << O << SourceRange(ModOrUse->getExprLoc()));
17850  UI.Diagnosed = true;
17851  }
17852 
17853  // A note on note{Pre, Post}{Use, Mod}:
17854  //
17855  // (It helps to follow the algorithm with an expression such as
17856  // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
17857  // operations before C++17 and both are well-defined in C++17).
17858  //
17859  // When visiting a node which uses/modify an object we first call notePreUse
17860  // or notePreMod before visiting its sub-expression(s). At this point the
17861  // children of the current node have not yet been visited and so the eventual
17862  // uses/modifications resulting from the children of the current node have not
17863  // been recorded yet.
17864  //
17865  // We then visit the children of the current node. After that notePostUse or
17866  // notePostMod is called. These will 1) detect an unsequenced modification
17867  // as side effect (as in "k++ + k") and 2) add a new usage with the
17868  // appropriate usage kind.
17869  //
17870  // We also have to be careful that some operation sequences modification as
17871  // side effect as well (for example: || or ,). To account for this we wrap
17872  // the visitation of such a sub-expression (for example: the LHS of || or ,)
17873  // with SequencedSubexpression. SequencedSubexpression is an RAII object
17874  // which record usages which are modifications as side effect, and then
17875  // downgrade them (or more accurately restore the previous usage which was a
17876  // modification as side effect) when exiting the scope of the sequenced
17877  // subexpression.
17878 
17879  void notePreUse(Object O, const Expr *UseExpr) {
17880  UsageInfo &UI = UsageMap[O];
17881  // Uses conflict with other modifications.
17882  checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
17883  }
17884 
17885  void notePostUse(Object O, const Expr *UseExpr) {
17886  UsageInfo &UI = UsageMap[O];
17887  checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
17888  /*IsModMod=*/false);
17889  addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
17890  }
17891 
17892  void notePreMod(Object O, const Expr *ModExpr) {
17893  UsageInfo &UI = UsageMap[O];
17894  // Modifications conflict with other modifications and with uses.
17895  checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
17896  checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
17897  }
17898 
17899  void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
17900  UsageInfo &UI = UsageMap[O];
17901  checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
17902  /*IsModMod=*/true);
17903  addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
17904  }
17905 
17906 public:
17907  SequenceChecker(Sema &S, const Expr *E,
17909  : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
17910  Visit(E);
17911  // Silence a -Wunused-private-field since WorkList is now unused.
17912  // TODO: Evaluate if it can be used, and if not remove it.
17913  (void)this->WorkList;
17914  }
17915 
17916  void VisitStmt(const Stmt *S) {
17917  // Skip all statements which aren't expressions for now.
17918  }
17919 
17920  void VisitExpr(const Expr *E) {
17921  // By default, just recurse to evaluated subexpressions.
17922  Base::VisitStmt(E);
17923  }
17924 
17925  void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
17926  for (auto *Sub : CSE->children()) {
17927  const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
17928  if (!ChildExpr)
17929  continue;
17930 
17931  if (ChildExpr == CSE->getOperand())
17932  // Do not recurse over a CoroutineSuspendExpr's operand.
17933  // The operand is also a subexpression of getCommonExpr(), and
17934  // recursing into it directly could confuse object management
17935  // for the sake of sequence tracking.
17936  continue;
17937 
17938  Visit(Sub);
17939  }
17940  }
17941 
17942  void VisitCastExpr(const CastExpr *E) {
17943  Object O = Object();
17944  if (E->getCastKind() == CK_LValueToRValue)
17945  O = getObject(E->getSubExpr(), false);
17946 
17947  if (O)
17948  notePreUse(O, E);
17949  VisitExpr(E);
17950  if (O)
17951  notePostUse(O, E);
17952  }
17953 
17954  void VisitSequencedExpressions(const Expr *SequencedBefore,
17955  const Expr *SequencedAfter) {
17956  SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
17957  SequenceTree::Seq AfterRegion = Tree.allocate(Region);
17958  SequenceTree::Seq OldRegion = Region;
17959 
17960  {
17961  SequencedSubexpression SeqBefore(*this);
17962  Region = BeforeRegion;
17963  Visit(SequencedBefore);
17964  }
17965 
17966  Region = AfterRegion;
17967  Visit(SequencedAfter);
17968 
17969  Region = OldRegion;
17970 
17971  Tree.merge(BeforeRegion);
17972  Tree.merge(AfterRegion);
17973  }
17974 
17975  void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
17976  // C++17 [expr.sub]p1:
17977  // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
17978  // expression E1 is sequenced before the expression E2.
17979  if (SemaRef.getLangOpts().CPlusPlus17)
17980  VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
17981  else {
17982  Visit(ASE->getLHS());
17983  Visit(ASE->getRHS());
17984  }
17985  }
17986 
17987  void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
17988  void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
17989  void VisitBinPtrMem(const BinaryOperator *BO) {
17990  // C++17 [expr.mptr.oper]p4:
17991  // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
17992  // the expression E1 is sequenced before the expression E2.
17993  if (SemaRef.getLangOpts().CPlusPlus17)
17994  VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
17995  else {
17996  Visit(BO->getLHS());
17997  Visit(BO->getRHS());
17998  }
17999  }
18000 
18001  void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
18002  void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
18003  void VisitBinShlShr(const BinaryOperator *BO) {
18004  // C++17 [expr.shift]p4:
18005  // The expression E1 is sequenced before the expression E2.
18006  if (SemaRef.getLangOpts().CPlusPlus17)
18007  VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
18008  else {
18009  Visit(BO->getLHS());
18010  Visit(BO->getRHS());
18011  }
18012  }
18013 
18014  void VisitBinComma(const BinaryOperator *BO) {
18015  // C++11 [expr.comma]p1:
18016  // Every value computation and side effect associated with the left
18017  // expression is sequenced before every value computation and side
18018  // effect associated with the right expression.
18019  VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
18020  }
18021 
18022  void VisitBinAssign(const BinaryOperator *BO) {
18023  SequenceTree::Seq RHSRegion;
18024  SequenceTree::Seq LHSRegion;
18025  if (SemaRef.getLangOpts().CPlusPlus17) {
18026  RHSRegion = Tree.allocate(Region);
18027  LHSRegion = Tree.allocate(Region);
18028  } else {
18029  RHSRegion = Region;
18030  LHSRegion = Region;
18031  }
18032  SequenceTree::Seq OldRegion = Region;
18033 
18034  // C++11 [expr.ass]p1:
18035  // [...] the assignment is sequenced after the value computation
18036  // of the right and left operands, [...]
18037  //
18038  // so check it before inspecting the operands and update the
18039  // map afterwards.
18040  Object O = getObject(BO->getLHS(), /*Mod=*/true);
18041  if (O)
18042  notePreMod(O, BO);
18043 
18044  if (SemaRef.getLangOpts().CPlusPlus17) {
18045  // C++17 [expr.ass]p1:
18046  // [...] The right operand is sequenced before the left operand. [...]
18047  {
18048  SequencedSubexpression SeqBefore(*this);
18049  Region = RHSRegion;
18050  Visit(BO->getRHS());
18051  }
18052 
18053  Region = LHSRegion;
18054  Visit(BO->getLHS());
18055 
18056  if (O && isa<CompoundAssignOperator>(BO))
18057  notePostUse(O, BO);
18058 
18059  } else {
18060  // C++11 does not specify any sequencing between the LHS and RHS.
18061  Region = LHSRegion;
18062  Visit(BO->getLHS());
18063 
18064  if (O && isa<CompoundAssignOperator>(BO))
18065  notePostUse(O, BO);
18066 
18067  Region = RHSRegion;
18068  Visit(BO->getRHS());
18069  }
18070 
18071  // C++11 [expr.ass]p1:
18072  // the assignment is sequenced [...] before the value computation of the
18073  // assignment expression.
18074  // C11 6.5.16/3 has no such rule.
18075  Region = OldRegion;
18076  if (O)
18077  notePostMod(O, BO,
18078  SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
18079  : UK_ModAsSideEffect);
18080  if (SemaRef.getLangOpts().CPlusPlus17) {
18081  Tree.merge(RHSRegion);
18082  Tree.merge(LHSRegion);
18083  }
18084  }
18085 
18086  void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
18087  VisitBinAssign(CAO);
18088  }
18089 
18090  void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
18091  void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
18092  void VisitUnaryPreIncDec(const UnaryOperator *UO) {
18093  Object O = getObject(UO->getSubExpr(), true);
18094  if (!O)
18095  return VisitExpr(UO);
18096 
18097  notePreMod(O, UO);
18098  Visit(UO->getSubExpr());
18099  // C++11 [expr.pre.incr]p1:
18100  // the expression ++x is equivalent to x+=1
18101  notePostMod(O, UO,
18102  SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
18103  : UK_ModAsSideEffect);
18104  }
18105 
18106  void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
18107  void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
18108  void VisitUnaryPostIncDec(const UnaryOperator *UO) {
18109  Object O = getObject(UO->getSubExpr(), true);
18110  if (!O)
18111  return VisitExpr(UO);
18112 
18113  notePreMod(O, UO);
18114  Visit(UO->getSubExpr());
18115  notePostMod(O, UO, UK_ModAsSideEffect);
18116  }
18117 
18118  void VisitBinLOr(const BinaryOperator *BO) {
18119  // C++11 [expr.log.or]p2:
18120  // If the second expression is evaluated, every value computation and
18121  // side effect associated with the first expression is sequenced before
18122  // every value computation and side effect associated with the
18123  // second expression.
18124  SequenceTree::Seq LHSRegion = Tree.allocate(Region);
18125  SequenceTree::Seq RHSRegion = Tree.allocate(Region);
18126  SequenceTree::Seq OldRegion = Region;
18127 
18128  EvaluationTracker Eval(*this);
18129  {
18130  SequencedSubexpression Sequenced(*this);
18131  Region = LHSRegion;
18132  Visit(BO->getLHS());
18133  }
18134 
18135  // C++11 [expr.log.or]p1:
18136  // [...] the second operand is not evaluated if the first operand
18137  // evaluates to true.
18138  bool EvalResult = false;
18139  bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
18140  bool ShouldVisitRHS = !EvalOK || !EvalResult;
18141  if (ShouldVisitRHS) {
18142  Region = RHSRegion;
18143  Visit(BO->getRHS());
18144  }
18145 
18146  Region = OldRegion;
18147  Tree.merge(LHSRegion);
18148  Tree.merge(RHSRegion);
18149  }
18150 
18151  void VisitBinLAnd(const BinaryOperator *BO) {
18152  // C++11 [expr.log.and]p2:
18153  // If the second expression is evaluated, every value computation and
18154  // side effect associated with the first expression is sequenced before
18155  // every value computation and side effect associated with the
18156  // second expression.
18157  SequenceTree::Seq LHSRegion = Tree.allocate(Region);
18158  SequenceTree::Seq RHSRegion = Tree.allocate(Region);
18159  SequenceTree::Seq OldRegion = Region;
18160 
18161  EvaluationTracker Eval(*this);
18162  {
18163  SequencedSubexpression Sequenced(*this);
18164  Region = LHSRegion;
18165  Visit(BO->getLHS());
18166  }
18167 
18168  // C++11 [expr.log.and]p1:
18169  // [...] the second operand is not evaluated if the first operand is false.
18170  bool EvalResult = false;
18171  bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
18172  bool ShouldVisitRHS = !EvalOK || EvalResult;
18173  if (ShouldVisitRHS) {
18174  Region = RHSRegion;
18175  Visit(BO->getRHS());
18176  }
18177 
18178  Region = OldRegion;
18179  Tree.merge(LHSRegion);
18180  Tree.merge(RHSRegion);
18181  }
18182 
18183  void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
18184  // C++11 [expr.cond]p1:
18185  // [...] Every value computation and side effect associated with the first
18186  // expression is sequenced before every value computation and side effect
18187  // associated with the second or third expression.
18188  SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
18189 
18190  // No sequencing is specified between the true and false expression.
18191  // However since exactly one of both is going to be evaluated we can
18192  // consider them to be sequenced. This is needed to avoid warning on
18193  // something like "x ? y+= 1 : y += 2;" in the case where we will visit
18194  // both the true and false expressions because we can't evaluate x.
18195  // This will still allow us to detect an expression like (pre C++17)
18196  // "(x ? y += 1 : y += 2) = y".
18197  //
18198  // We don't wrap the visitation of the true and false expression with
18199  // SequencedSubexpression because we don't want to downgrade modifications
18200  // as side effect in the true and false expressions after the visition
18201  // is done. (for example in the expression "(x ? y++ : y++) + y" we should
18202  // not warn between the two "y++", but we should warn between the "y++"
18203  // and the "y".
18204  SequenceTree::Seq TrueRegion = Tree.allocate(Region);
18205  SequenceTree::Seq FalseRegion = Tree.allocate(Region);
18206  SequenceTree::Seq OldRegion = Region;
18207 
18208  EvaluationTracker Eval(*this);
18209  {
18210  SequencedSubexpression Sequenced(*this);
18211  Region = ConditionRegion;
18212  Visit(CO->getCond());
18213  }
18214 
18215  // C++11 [expr.cond]p1:
18216  // [...] The first expression is contextually converted to bool (Clause 4).
18217  // It is evaluated and if it is true, the result of the conditional
18218  // expression is the value of the second expression, otherwise that of the
18219  // third expression. Only one of the second and third expressions is
18220  // evaluated. [...]
18221  bool EvalResult = false;
18222  bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
18223  bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
18224  bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
18225  if (ShouldVisitTrueExpr) {
18226  Region = TrueRegion;
18227  Visit(CO->getTrueExpr());
18228  }
18229  if (ShouldVisitFalseExpr) {
18230  Region = FalseRegion;
18231  Visit(CO->getFalseExpr());
18232  }
18233 
18234  Region = OldRegion;
18235  Tree.merge(ConditionRegion);
18236  Tree.merge(TrueRegion);
18237  Tree.merge(FalseRegion);
18238  }
18239 
18240  void VisitCallExpr(const CallExpr *CE) {
18241  // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
18242 
18243  if (CE->isUnevaluatedBuiltinCall(Context))
18244  return;
18245 
18246  // C++11 [intro.execution]p15:
18247  // When calling a function [...], every value computation and side effect
18248  // associated with any argument expression, or with the postfix expression
18249  // designating the called function, is sequenced before execution of every
18250  // expression or statement in the body of the function [and thus before
18251  // the value computation of its result].
18252  SequencedSubexpression Sequenced(*this);
18253  SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
18254  // C++17 [expr.call]p5
18255  // The postfix-expression is sequenced before each expression in the
18256  // expression-list and any default argument. [...]
18257  SequenceTree::Seq CalleeRegion;
18258  SequenceTree::Seq OtherRegion;
18259  if (SemaRef.getLangOpts().CPlusPlus17) {
18260  CalleeRegion = Tree.allocate(Region);
18261  OtherRegion = Tree.allocate(Region);
18262  } else {
18263  CalleeRegion = Region;
18264  OtherRegion = Region;
18265  }
18266  SequenceTree::Seq OldRegion = Region;
18267 
18268  // Visit the callee expression first.
18269  Region = CalleeRegion;
18270  if (SemaRef.getLangOpts().CPlusPlus17) {
18271  SequencedSubexpression Sequenced(*this);
18272  Visit(CE->getCallee());
18273  } else {
18274  Visit(CE->getCallee());
18275  }
18276 
18277  // Then visit the argument expressions.
18278  Region = OtherRegion;
18279  for (const Expr *Argument : CE->arguments())
18280  Visit(Argument);
18281 
18282  Region = OldRegion;
18283  if (SemaRef.getLangOpts().CPlusPlus17) {
18284  Tree.merge(CalleeRegion);
18285  Tree.merge(OtherRegion);
18286  }
18287  });
18288  }
18289 
18290  void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
18291  // C++17 [over.match.oper]p2:
18292  // [...] the operator notation is first transformed to the equivalent
18293  // function-call notation as summarized in Table 12 (where @ denotes one
18294  // of the operators covered in the specified subclause). However, the
18295  // operands are sequenced in the order prescribed for the built-in
18296  // operator (Clause 8).
18297  //
18298  // From the above only overloaded binary operators and overloaded call
18299  // operators have sequencing rules in C++17 that we need to handle
18300  // separately.
18301  if (!SemaRef.getLangOpts().CPlusPlus17 ||
18302  (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
18303  return VisitCallExpr(CXXOCE);
18304 
18305  enum {
18306  NoSequencing,
18307  LHSBeforeRHS,
18308  RHSBeforeLHS,
18309  LHSBeforeRest
18310  } SequencingKind;
18311  switch (CXXOCE->getOperator()) {
18312  case OO_Equal:
18313  case OO_PlusEqual:
18314  case OO_MinusEqual:
18315  case OO_StarEqual:
18316  case OO_SlashEqual:
18317  case OO_PercentEqual:
18318  case OO_CaretEqual:
18319  case OO_AmpEqual:
18320  case OO_PipeEqual:
18321  case OO_LessLessEqual:
18322  case OO_GreaterGreaterEqual:
18323  SequencingKind = RHSBeforeLHS;
18324  break;
18325 
18326  case OO_LessLess:
18327  case OO_GreaterGreater:
18328  case OO_AmpAmp:
18329  case OO_PipePipe:
18330  case OO_Comma:
18331  case OO_ArrowStar:
18332  case OO_Subscript:
18333  SequencingKind = LHSBeforeRHS;
18334  break;
18335 
18336  case OO_Call:
18337  SequencingKind = LHSBeforeRest;
18338  break;
18339 
18340  default:
18341  SequencingKind = NoSequencing;
18342  break;
18343  }
18344 
18345  if (SequencingKind == NoSequencing)
18346  return VisitCallExpr(CXXOCE);
18347 
18348  // This is a call, so all subexpressions are sequenced before the result.
18349  SequencedSubexpression Sequenced(*this);
18350 
18351  SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
18352  assert(SemaRef.getLangOpts().CPlusPlus17 &&
18353  "Should only get there with C++17 and above!");
18354  assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
18355  "Should only get there with an overloaded binary operator"
18356  " or an overloaded call operator!");
18357 
18358  if (SequencingKind == LHSBeforeRest) {
18359  assert(CXXOCE->getOperator() == OO_Call &&
18360  "We should only have an overloaded call operator here!");
18361 
18362  // This is very similar to VisitCallExpr, except that we only have the
18363  // C++17 case. The postfix-expression is the first argument of the
18364  // CXXOperatorCallExpr. The expressions in the expression-list, if any,
18365  // are in the following arguments.
18366  //
18367  // Note that we intentionally do not visit the callee expression since
18368  // it is just a decayed reference to a function.
18369  SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
18370  SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
18371  SequenceTree::Seq OldRegion = Region;
18372 
18373  assert(CXXOCE->getNumArgs() >= 1 &&
18374  "An overloaded call operator must have at least one argument"
18375  " for the postfix-expression!");
18376  const Expr *PostfixExpr = CXXOCE->getArgs()[0];
18377  llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
18378  CXXOCE->getNumArgs() - 1);
18379 
18380  // Visit the postfix-expression first.
18381  {
18382  Region = PostfixExprRegion;
18383  SequencedSubexpression Sequenced(*this);
18384  Visit(PostfixExpr);
18385  }
18386 
18387  // Then visit the argument expressions.
18388  Region = ArgsRegion;
18389  for (const Expr *Arg : Args)
18390  Visit(Arg);
18391 
18392  Region = OldRegion;
18393  Tree.merge(PostfixExprRegion);
18394  Tree.merge(ArgsRegion);
18395  } else {
18396  assert(CXXOCE->getNumArgs() == 2 &&
18397  "Should only have two arguments here!");
18398  assert((SequencingKind == LHSBeforeRHS ||
18399  SequencingKind == RHSBeforeLHS) &&
18400  "Unexpected sequencing kind!");
18401 
18402  // We do not visit the callee expression since it is just a decayed
18403  // reference to a function.
18404  const Expr *E1 = CXXOCE->getArg(0);
18405  const Expr *E2 = CXXOCE->getArg(1);
18406  if (SequencingKind == RHSBeforeLHS)
18407  std::swap(E1, E2);
18408 
18409  return VisitSequencedExpressions(E1, E2);
18410  }
18411  });
18412  }
18413 
18414  void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
18415  // This is a call, so all subexpressions are sequenced before the result.
18416  SequencedSubexpression Sequenced(*this);
18417 
18418  if (!CCE->isListInitialization())
18419  return VisitExpr(CCE);
18420 
18421  // In C++11, list initializations are sequenced.
18422  SequenceExpressionsInOrder(
18423  llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
18424  }
18425 
18426  void VisitInitListExpr(const InitListExpr *ILE) {
18427  if (!SemaRef.getLangOpts().CPlusPlus11)
18428  return VisitExpr(ILE);
18429 
18430  // In C++11, list initializations are sequenced.
18431  SequenceExpressionsInOrder(ILE->inits());
18432  }
18433 
18434  void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
18435  // C++20 parenthesized list initializations are sequenced. See C++20
18436  // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
18437  SequenceExpressionsInOrder(PLIE->getInitExprs());
18438  }
18439 
18440 private:
18441  void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
18443  SequenceTree::Seq Parent = Region;
18444  for (const Expr *E : ExpressionList) {
18445  if (!E)
18446  continue;
18447  Region = Tree.allocate(Parent);
18448  Elts.push_back(Region);
18449  Visit(E);
18450  }
18451 
18452  // Forget that the initializers are sequenced.
18453  Region = Parent;
18454  for (unsigned I = 0; I < Elts.size(); ++I)
18455  Tree.merge(Elts[I]);
18456  }
18457 };
18458 
18459 SequenceChecker::UsageInfo::UsageInfo() = default;
18460 
18461 } // namespace
18462 
18463 void Sema::CheckUnsequencedOperations(const Expr *E) {
18465  WorkList.push_back(E);
18466  while (!WorkList.empty()) {
18467  const Expr *Item = WorkList.pop_back_val();
18468  SequenceChecker(*this, Item, WorkList);
18469  }
18470 }
18471 
18472 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
18473  bool IsConstexpr) {
18474  llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
18475  IsConstexpr || isa<ConstantExpr>(E));
18476  CheckImplicitConversions(E, CheckLoc);
18477  if (!E->isInstantiationDependent())
18478  CheckUnsequencedOperations(E);
18479  if (!IsConstexpr && !E->isValueDependent())
18480  CheckForIntOverflow(E);
18481  DiagnoseMisalignedMembers();
18482 }
18483 
18484 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
18485  FieldDecl *BitField,
18486  Expr *Init) {
18487  (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
18488 }
18489 
18491  SourceLocation Loc) {
18492  if (!PType->isVariablyModifiedType())
18493  return;
18494  if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
18495  diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
18496  return;
18497  }
18498  if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
18499  diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
18500  return;
18501  }
18502  if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
18503  diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
18504  return;
18505  }
18506 
18507  const ArrayType *AT = S.Context.getAsArrayType(PType);
18508  if (!AT)
18509  return;
18510 
18513  return;
18514  }
18515 
18516  S.Diag(Loc, diag::err_array_star_in_function_definition);
18517 }
18518 
18519 /// CheckParmsForFunctionDef - Check that the parameters of the given
18520 /// function are appropriate for the definition of a function. This
18521 /// takes care of any checks that cannot be performed on the
18522 /// declaration itself, e.g., that the types of each of the function
18523 /// parameters are complete.
18525  bool CheckParameterNames) {
18526  bool HasInvalidParm = false;
18527  for (ParmVarDecl *Param : Parameters) {
18528  assert(Param && "null in a parameter list");
18529  // C99 6.7.5.3p4: the parameters in a parameter type list in a
18530  // function declarator that is part of a function definition of
18531  // that function shall not have incomplete type.
18532  //
18533  // C++23 [dcl.fct.def.general]/p2
18534  // The type of a parameter [...] for a function definition
18535  // shall not be a (possibly cv-qualified) class type that is incomplete
18536  // or abstract within the function body unless the function is deleted.
18537  if (!Param->isInvalidDecl() &&
18538  (RequireCompleteType(Param->getLocation(), Param->getType(),
18539  diag::err_typecheck_decl_incomplete_type) ||
18540  RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
18541  diag::err_abstract_type_in_decl,
18542  AbstractParamType))) {
18543  Param->setInvalidDecl();
18544  HasInvalidParm = true;
18545  }
18546 
18547  // C99 6.9.1p5: If the declarator includes a parameter type list, the
18548  // declaration of each parameter shall include an identifier.
18549  if (CheckParameterNames && Param->getIdentifier() == nullptr &&
18550  !Param->isImplicit() && !getLangOpts().CPlusPlus) {
18551  // Diagnose this as an extension in C17 and earlier.
18552  if (!getLangOpts().C23)
18553  Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
18554  }
18555 
18556  // C99 6.7.5.3p12:
18557  // If the function declarator is not part of a definition of that
18558  // function, parameters may have incomplete type and may use the [*]
18559  // notation in their sequences of declarator specifiers to specify
18560  // variable length array types.
18561  QualType PType = Param->getOriginalType();
18562  // FIXME: This diagnostic should point the '[*]' if source-location
18563  // information is added for it.
18564  diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
18565 
18566  // If the parameter is a c++ class type and it has to be destructed in the
18567  // callee function, declare the destructor so that it can be called by the
18568  // callee function. Do not perform any direct access check on the dtor here.
18569  if (!Param->isInvalidDecl()) {
18570  if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
18571  if (!ClassDecl->isInvalidDecl() &&
18572  !ClassDecl->hasIrrelevantDestructor() &&
18573  !ClassDecl->isDependentContext() &&
18574  ClassDecl->isParamDestroyedInCallee()) {
18575  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
18576  MarkFunctionReferenced(Param->getLocation(), Destructor);
18577  DiagnoseUseOfDecl(Destructor, Param->getLocation());
18578  }
18579  }
18580  }
18581 
18582  // Parameters with the pass_object_size attribute only need to be marked
18583  // constant at function definitions. Because we lack information about
18584  // whether we're on a declaration or definition when we're instantiating the
18585  // attribute, we need to check for constness here.
18586  if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
18587  if (!Param->getType().isConstQualified())
18588  Diag(Param->getLocation(), diag::err_attribute_pointers_only)
18589  << Attr->getSpelling() << 1;
18590 
18591  // Check for parameter names shadowing fields from the class.
18592  if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
18593  // The owning context for the parameter should be the function, but we
18594  // want to see if this function's declaration context is a record.
18595  DeclContext *DC = Param->getDeclContext();
18596  if (DC && DC->isFunctionOrMethod()) {
18597  if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
18598  CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
18599  RD, /*DeclIsField*/ false);
18600  }
18601  }
18602 
18603  if (!Param->isInvalidDecl() &&
18604  Param->getOriginalType()->isWebAssemblyTableType()) {
18605  Param->setInvalidDecl();
18606  HasInvalidParm = true;
18607  Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
18608  }
18609  }
18610 
18611  return HasInvalidParm;
18612 }
18613 
18614 std::optional<std::pair<
18616  *E,
18617  ASTContext
18618  &Ctx);
18619 
18620 /// Compute the alignment and offset of the base class object given the
18621 /// derived-to-base cast expression and the alignment and offset of the derived
18622 /// class object.
18623 static std::pair<CharUnits, CharUnits>
18625  CharUnits BaseAlignment, CharUnits Offset,
18626  ASTContext &Ctx) {
18627  for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
18628  ++PathI) {
18629  const CXXBaseSpecifier *Base = *PathI;
18630  const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
18631  if (Base->isVirtual()) {
18632  // The complete object may have a lower alignment than the non-virtual
18633  // alignment of the base, in which case the base may be misaligned. Choose
18634  // the smaller of the non-virtual alignment and BaseAlignment, which is a
18635  // conservative lower bound of the complete object alignment.
18636  CharUnits NonVirtualAlignment =
18638  BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
18639  Offset = CharUnits::Zero();
18640  } else {
18641  const ASTRecordLayout &RL =
18642  Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
18643  Offset += RL.getBaseClassOffset(BaseDecl);
18644  }
18645  DerivedType = Base->getType();
18646  }
18647 
18648  return std::make_pair(BaseAlignment, Offset);
18649 }
18650 
18651 /// Compute the alignment and offset of a binary additive operator.
18652 static std::optional<std::pair<CharUnits, CharUnits>>
18654  bool IsSub, ASTContext &Ctx) {
18655  QualType PointeeType = PtrE->getType()->getPointeeType();
18656 
18657  if (!PointeeType->isConstantSizeType())
18658  return std::nullopt;
18659 
18660  auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
18661 
18662  if (!P)
18663  return std::nullopt;
18664 
18665  CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
18666  if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
18667  CharUnits Offset = EltSize * IdxRes->getExtValue();
18668  if (IsSub)
18669  Offset = -Offset;
18670  return std::make_pair(P->first, P->second + Offset);
18671  }
18672 
18673  // If the integer expression isn't a constant expression, compute the lower
18674  // bound of the alignment using the alignment and offset of the pointer
18675  // expression and the element size.
18676  return std::make_pair(
18677  P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
18678  CharUnits::Zero());
18679 }
18680 
18681 /// This helper function takes an lvalue expression and returns the alignment of
18682 /// a VarDecl and a constant offset from the VarDecl.
18683 std::optional<std::pair<
18684  CharUnits,
18686  ASTContext &Ctx) {
18687  E = E->IgnoreParens();
18688  switch (E->getStmtClass()) {
18689  default:
18690  break;
18691  case Stmt::CStyleCastExprClass:
18692  case Stmt::CXXStaticCastExprClass:
18693  case Stmt::ImplicitCastExprClass: {
18694  auto *CE = cast<CastExpr>(E);
18695  const Expr *From = CE->getSubExpr();
18696  switch (CE->getCastKind()) {
18697  default:
18698  break;
18699  case CK_NoOp:
18700  return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
18701  case CK_UncheckedDerivedToBase:
18702  case CK_DerivedToBase: {
18703  auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
18704  if (!P)
18705  break;
18706  return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
18707  P->second, Ctx);
18708  }
18709  }
18710  break;
18711  }
18712  case Stmt::ArraySubscriptExprClass: {
18713  auto *ASE = cast<ArraySubscriptExpr>(E);
18714  return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
18715  false, Ctx);
18716  }
18717  case Stmt::DeclRefExprClass: {
18718  if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
18719  // FIXME: If VD is captured by copy or is an escaping __block variable,
18720  // use the alignment of VD's type.
18721  if (!VD->getType()->isReferenceType()) {
18722  // Dependent alignment cannot be resolved -> bail out.
18723  if (VD->hasDependentAlignment())
18724  break;
18725  return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
18726  }
18727  if (VD->hasInit())
18728  return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
18729  }
18730  break;
18731  }
18732  case Stmt::MemberExprClass: {
18733  auto *ME = cast<MemberExpr>(E);
18734  auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
18735  if (!FD || FD->getType()->isReferenceType() ||
18736  FD->getParent()->isInvalidDecl())
18737  break;
18738  std::optional<std::pair<CharUnits, CharUnits>> P;
18739  if (ME->isArrow())
18740  P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
18741  else
18742  P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
18743  if (!P)
18744  break;
18745  const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
18746  uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
18747  return std::make_pair(P->first,
18748  P->second + CharUnits::fromQuantity(Offset));
18749  }
18750  case Stmt::UnaryOperatorClass: {
18751  auto *UO = cast<UnaryOperator>(E);
18752  switch (UO->getOpcode()) {
18753  default:
18754  break;
18755  case UO_Deref:
18756  return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
18757  }
18758  break;
18759  }
18760  case Stmt::BinaryOperatorClass: {
18761  auto *BO = cast<BinaryOperator>(E);
18762  auto Opcode = BO->getOpcode();
18763  switch (Opcode) {
18764  default:
18765  break;
18766  case BO_Comma:
18767  return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
18768  }
18769  break;
18770  }
18771  }
18772  return std::nullopt;
18773 }
18774 
18775 /// This helper function takes a pointer expression and returns the alignment of
18776 /// a VarDecl and a constant offset from the VarDecl.
18777 std::optional<std::pair<
18779  *E,
18780  ASTContext
18781  &Ctx) {
18782  E = E->IgnoreParens();
18783  switch (E->getStmtClass()) {
18784  default:
18785  break;
18786  case Stmt::CStyleCastExprClass:
18787  case Stmt::CXXStaticCastExprClass:
18788  case Stmt::ImplicitCastExprClass: {
18789  auto *CE = cast<CastExpr>(E);
18790  const Expr *From = CE->getSubExpr();
18791  switch (CE->getCastKind()) {
18792  default:
18793  break;
18794  case CK_NoOp:
18795  return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
18796  case CK_ArrayToPointerDecay:
18797  return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
18798  case CK_UncheckedDerivedToBase:
18799  case CK_DerivedToBase: {
18800  auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
18801  if (!P)
18802  break;
18804  CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
18805  }
18806  }
18807  break;
18808  }
18809  case Stmt::CXXThisExprClass: {
18810  auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
18811  CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
18812  return std::make_pair(Alignment, CharUnits::Zero());
18813  }
18814  case Stmt::UnaryOperatorClass: {
18815  auto *UO = cast<UnaryOperator>(E);
18816  if (UO->getOpcode() == UO_AddrOf)
18818  break;
18819  }
18820  case Stmt::BinaryOperatorClass: {
18821  auto *BO = cast<BinaryOperator>(E);
18822  auto Opcode = BO->getOpcode();
18823  switch (Opcode) {
18824  default:
18825  break;
18826  case BO_Add:
18827  case BO_Sub: {
18828  const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
18829  if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
18830  std::swap(LHS, RHS);
18831  return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
18832  Ctx);
18833  }
18834  case BO_Comma:
18835  return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
18836  }
18837  break;
18838  }
18839  }
18840  return std::nullopt;
18841 }
18842 
18844  // See if we can compute the alignment of a VarDecl and an offset from it.
18845  std::optional<std::pair<CharUnits, CharUnits>> P =
18847 
18848  if (P)
18849  return P->first.alignmentAtOffset(P->second);
18850 
18851  // If that failed, return the type's alignment.
18853 }
18854 
18855 /// CheckCastAlign - Implements -Wcast-align, which warns when a
18856 /// pointer cast increases the alignment requirements.
18858  // This is actually a lot of work to potentially be doing on every
18859  // cast; don't do it if we're ignoring -Wcast_align (as is the default).
18860  if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
18861  return;
18862 
18863  // Ignore dependent types.
18864  if (T->isDependentType() || Op->getType()->isDependentType())
18865  return;
18866 
18867  // Require that the destination be a pointer type.
18868  const PointerType *DestPtr = T->getAs<PointerType>();
18869  if (!DestPtr) return;
18870 
18871  // If the destination has alignment 1, we're done.
18872  QualType DestPointee = DestPtr->getPointeeType();
18873  if (DestPointee->isIncompleteType()) return;
18874  CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
18875  if (DestAlign.isOne()) return;
18876 
18877  // Require that the source be a pointer type.
18878  const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
18879  if (!SrcPtr) return;
18880  QualType SrcPointee = SrcPtr->getPointeeType();
18881 
18882  // Explicitly allow casts from cv void*. We already implicitly
18883  // allowed casts to cv void*, since they have alignment 1.
18884  // Also allow casts involving incomplete types, which implicitly
18885  // includes 'void'.
18886  if (SrcPointee->isIncompleteType()) return;
18887 
18888  CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
18889 
18890  if (SrcAlign >= DestAlign) return;
18891 
18892  Diag(TRange.getBegin(), diag::warn_cast_align)
18893  << Op->getType() << T
18894  << static_cast<unsigned>(SrcAlign.getQuantity())
18895  << static_cast<unsigned>(DestAlign.getQuantity())
18896  << TRange << Op->getSourceRange();
18897 }
18898 
18899 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
18900  const ArraySubscriptExpr *ASE,
18901  bool AllowOnePastEnd, bool IndexNegated) {
18902  // Already diagnosed by the constant evaluator.
18903  if (isConstantEvaluatedContext())
18904  return;
18905 
18906  IndexExpr = IndexExpr->IgnoreParenImpCasts();
18907  if (IndexExpr->isValueDependent())
18908  return;
18909 
18910  const Type *EffectiveType =
18911  BaseExpr->getType()->getPointeeOrArrayElementType();
18912  BaseExpr = BaseExpr->IgnoreParenCasts();
18913  const ConstantArrayType *ArrayTy =
18914  Context.getAsConstantArrayType(BaseExpr->getType());
18915 
18917  StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
18918 
18919  const Type *BaseType =
18920  ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
18921  bool IsUnboundedArray =
18922  BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
18923  Context, StrictFlexArraysLevel,
18924  /*IgnoreTemplateOrMacroSubstitution=*/true);
18925  if (EffectiveType->isDependentType() ||
18926  (!IsUnboundedArray && BaseType->isDependentType()))
18927  return;
18928 
18929  Expr::EvalResult Result;
18930  if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
18931  return;
18932 
18933  llvm::APSInt index = Result.Val.getInt();
18934  if (IndexNegated) {
18935  index.setIsUnsigned(false);
18936  index = -index;
18937  }
18938 
18939  if (IsUnboundedArray) {
18940  if (EffectiveType->isFunctionType())
18941  return;
18942  if (index.isUnsigned() || !index.isNegative()) {
18943  const auto &ASTC = getASTContext();
18944  unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
18945  EffectiveType->getCanonicalTypeInternal().getAddressSpace());
18946  if (index.getBitWidth() < AddrBits)
18947  index = index.zext(AddrBits);
18948  std::optional<CharUnits> ElemCharUnits =
18949  ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
18950  // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
18951  // pointer) bounds-checking isn't meaningful.
18952  if (!ElemCharUnits || ElemCharUnits->isZero())
18953  return;
18954  llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
18955  // If index has more active bits than address space, we already know
18956  // we have a bounds violation to warn about. Otherwise, compute
18957  // address of (index + 1)th element, and warn about bounds violation
18958  // only if that address exceeds address space.
18959  if (index.getActiveBits() <= AddrBits) {
18960  bool Overflow;
18961  llvm::APInt Product(index);
18962  Product += 1;
18963  Product = Product.umul_ov(ElemBytes, Overflow);
18964  if (!Overflow && Product.getActiveBits() <= AddrBits)
18965  return;
18966  }
18967 
18968  // Need to compute max possible elements in address space, since that
18969  // is included in diag message.
18970  llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
18971  MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
18972  MaxElems += 1;
18973  ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
18974  MaxElems = MaxElems.udiv(ElemBytes);
18975 
18976  unsigned DiagID =
18977  ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
18978  : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
18979 
18980  // Diag message shows element size in bits and in "bytes" (platform-
18981  // dependent CharUnits)
18982  DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
18983  PDiag(DiagID)
18984  << toString(index, 10, true) << AddrBits
18985  << (unsigned)ASTC.toBits(*ElemCharUnits)
18986  << toString(ElemBytes, 10, false)
18987  << toString(MaxElems, 10, false)
18988  << (unsigned)MaxElems.getLimitedValue(~0U)
18989  << IndexExpr->getSourceRange());
18990 
18991  const NamedDecl *ND = nullptr;
18992  // Try harder to find a NamedDecl to point at in the note.
18993  while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
18994  BaseExpr = ASE->getBase()->IgnoreParenCasts();
18995  if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
18996  ND = DRE->getDecl();
18997  if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
18998  ND = ME->getMemberDecl();
18999 
19000  if (ND)
19001  DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
19002  PDiag(diag::note_array_declared_here) << ND);
19003  }
19004  return;
19005  }
19006 
19007  if (index.isUnsigned() || !index.isNegative()) {
19008  // It is possible that the type of the base expression after
19009  // IgnoreParenCasts is incomplete, even though the type of the base
19010  // expression before IgnoreParenCasts is complete (see PR39746 for an
19011  // example). In this case we have no information about whether the array
19012  // access exceeds the array bounds. However we can still diagnose an array
19013  // access which precedes the array bounds.
19014  if (BaseType->isIncompleteType())
19015  return;
19016 
19017  llvm::APInt size = ArrayTy->getSize();
19018 
19019  if (BaseType != EffectiveType) {
19020  // Make sure we're comparing apples to apples when comparing index to
19021  // size.
19022  uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
19023  uint64_t array_typesize = Context.getTypeSize(BaseType);
19024 
19025  // Handle ptrarith_typesize being zero, such as when casting to void*.
19026  // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
19027  if (!ptrarith_typesize)
19028  ptrarith_typesize = Context.getCharWidth();
19029 
19030  if (ptrarith_typesize != array_typesize) {
19031  // There's a cast to a different size type involved.
19032  uint64_t ratio = array_typesize / ptrarith_typesize;
19033 
19034  // TODO: Be smarter about handling cases where array_typesize is not a
19035  // multiple of ptrarith_typesize.
19036  if (ptrarith_typesize * ratio == array_typesize)
19037  size *= llvm::APInt(size.getBitWidth(), ratio);
19038  }
19039  }
19040 
19041  if (size.getBitWidth() > index.getBitWidth())
19042  index = index.zext(size.getBitWidth());
19043  else if (size.getBitWidth() < index.getBitWidth())
19044  size = size.zext(index.getBitWidth());
19045 
19046  // For array subscripting the index must be less than size, but for pointer
19047  // arithmetic also allow the index (offset) to be equal to size since
19048  // computing the next address after the end of the array is legal and
19049  // commonly done e.g. in C++ iterators and range-based for loops.
19050  if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
19051  return;
19052 
19053  // Suppress the warning if the subscript expression (as identified by the
19054  // ']' location) and the index expression are both from macro expansions
19055  // within a system header.
19056  if (ASE) {
19057  SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
19058  ASE->getRBracketLoc());
19059  if (SourceMgr.isInSystemHeader(RBracketLoc)) {
19060  SourceLocation IndexLoc =
19061  SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
19062  if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
19063  return;
19064  }
19065  }
19066 
19067  unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
19068  : diag::warn_ptr_arith_exceeds_bounds;
19069  unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
19070  QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
19071 
19072  DiagRuntimeBehavior(
19073  BaseExpr->getBeginLoc(), BaseExpr,
19074  PDiag(DiagID) << toString(index, 10, true) << ArrayTy->desugar()
19075  << CastMsg << CastMsgTy << IndexExpr->getSourceRange());
19076  } else {
19077  unsigned DiagID = diag::warn_array_index_precedes_bounds;
19078  if (!ASE) {
19079  DiagID = diag::warn_ptr_arith_precedes_bounds;
19080  if (index.isNegative()) index = -index;
19081  }
19082 
19083  DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
19084  PDiag(DiagID) << toString(index, 10, true)
19085  << IndexExpr->getSourceRange());
19086  }
19087 
19088  const NamedDecl *ND = nullptr;
19089  // Try harder to find a NamedDecl to point at in the note.
19090  while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
19091  BaseExpr = ASE->getBase()->IgnoreParenCasts();
19092  if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
19093  ND = DRE->getDecl();
19094  if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
19095  ND = ME->getMemberDecl();
19096 
19097  if (ND)
19098  DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
19099  PDiag(diag::note_array_declared_here) << ND);
19100 }
19101 
19102 void Sema::CheckArrayAccess(const Expr *expr) {
19103  int AllowOnePastEnd = 0;
19104  while (expr) {
19105  expr = expr->IgnoreParenImpCasts();
19106  switch (expr->getStmtClass()) {
19107  case Stmt::ArraySubscriptExprClass: {
19108  const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
19109  CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
19110  AllowOnePastEnd > 0);
19111  expr = ASE->getBase();
19112  break;
19113  }
19114  case Stmt::MemberExprClass: {
19115  expr = cast<MemberExpr>(expr)->getBase();
19116  break;
19117  }
19118  case Stmt::OMPArraySectionExprClass: {
19119  const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
19120  if (ASE->getLowerBound())
19121  CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
19122  /*ASE=*/nullptr, AllowOnePastEnd > 0);
19123  return;
19124  }
19125  case Stmt::UnaryOperatorClass: {
19126  // Only unwrap the * and & unary operators
19127  const UnaryOperator *UO = cast<UnaryOperator>(expr);
19128  expr = UO->getSubExpr();
19129  switch (UO->getOpcode()) {
19130  case UO_AddrOf:
19131  AllowOnePastEnd++;
19132  break;
19133  case UO_Deref:
19134  AllowOnePastEnd--;
19135  break;
19136  default:
19137  return;
19138  }
19139  break;
19140  }
19141  case Stmt::ConditionalOperatorClass: {
19142  const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
19143  if (const Expr *lhs = cond->getLHS())
19144  CheckArrayAccess(lhs);
19145  if (const Expr *rhs = cond->getRHS())
19146  CheckArrayAccess(rhs);
19147  return;
19148  }
19149  case Stmt::CXXOperatorCallExprClass: {
19150  const auto *OCE = cast<CXXOperatorCallExpr>(expr);
19151  for (const auto *Arg : OCE->arguments())
19152  CheckArrayAccess(Arg);
19153  return;
19154  }
19155  default:
19156  return;
19157  }
19158  }
19159 }
19160 
19161 //===--- CHECK: Objective-C retain cycles ----------------------------------//
19162 
19163 namespace {
19164 
19165 struct RetainCycleOwner {
19166  VarDecl *Variable = nullptr;
19168  SourceLocation Loc;
19169  bool Indirect = false;
19170 
19171  RetainCycleOwner() = default;
19172 
19173  void setLocsFrom(Expr *e) {
19174  Loc = e->getExprLoc();
19175  Range = e->getSourceRange();
19176  }
19177 };
19178 
19179 } // namespace
19180 
19181 /// Consider whether capturing the given variable can possibly lead to
19182 /// a retain cycle.
19183 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
19184  // In ARC, it's captured strongly iff the variable has __strong
19185  // lifetime. In MRR, it's captured strongly if the variable is
19186  // __block and has an appropriate type.
19187  if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
19188  return false;
19189 
19190  owner.Variable = var;
19191  if (ref)
19192  owner.setLocsFrom(ref);
19193  return true;
19194 }
19195 
19196 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
19197  while (true) {
19198  e = e->IgnoreParens();
19199  if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
19200  switch (cast->getCastKind()) {
19201  case CK_BitCast:
19202  case CK_LValueBitCast:
19203  case CK_LValueToRValue:
19204  case CK_ARCReclaimReturnedObject:
19205  e = cast->getSubExpr();
19206  continue;
19207 
19208  default:
19209  return false;
19210  }
19211  }
19212 
19213  if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
19214  ObjCIvarDecl *ivar = ref->getDecl();
19216  return false;
19217 
19218  // Try to find a retain cycle in the base.
19219  if (!findRetainCycleOwner(S, ref->getBase(), owner))
19220  return false;
19221 
19222  if (ref->isFreeIvar()) owner.setLocsFrom(ref);
19223  owner.Indirect = true;
19224  return true;
19225  }
19226 
19227  if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
19228  VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
19229  if (!var) return false;
19230  return considerVariable(var, ref, owner);
19231  }
19232 
19233  if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
19234  if (member->isArrow()) return false;
19235 
19236  // Don't count this as an indirect ownership.
19237  e = member->getBase();
19238  continue;
19239  }
19240 
19241  if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
19242  // Only pay attention to pseudo-objects on property references.
19243  ObjCPropertyRefExpr *pre
19244  = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
19245  ->IgnoreParens());
19246  if (!pre) return false;
19247  if (pre->isImplicitProperty()) return false;
19248  ObjCPropertyDecl *property = pre->getExplicitProperty();
19249  if (!property->isRetaining() &&
19250  !(property->getPropertyIvarDecl() &&
19251  property->getPropertyIvarDecl()->getType()
19252  .getObjCLifetime() == Qualifiers::OCL_Strong))
19253  return false;
19254 
19255  owner.Indirect = true;
19256  if (pre->isSuperReceiver()) {
19257  owner.Variable = S.getCurMethodDecl()->getSelfDecl();
19258  if (!owner.Variable)
19259  return false;
19260  owner.Loc = pre->getLocation();
19261  owner.Range = pre->getSourceRange();
19262  return true;
19263  }
19264  e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
19265  ->getSourceExpr());
19266  continue;
19267  }
19268 
19269  // Array ivars?
19270 
19271  return false;
19272  }
19273 }
19274 
19275 namespace {
19276 
19277  struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
19278  VarDecl *Variable;
19279  Expr *Capturer = nullptr;
19280  bool VarWillBeReased = false;
19281 
19282  FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
19283  : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
19284  Variable(variable) {}
19285 
19286  void VisitDeclRefExpr(DeclRefExpr *ref) {
19287  if (ref->getDecl() == Variable && !Capturer)
19288  Capturer = ref;
19289  }
19290 
19291  void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
19292  if (Capturer) return;
19293  Visit(ref->getBase());
19294  if (Capturer && ref->isFreeIvar())
19295  Capturer = ref;
19296  }
19297 
19298  void VisitBlockExpr(BlockExpr *block) {
19299  // Look inside nested blocks
19300  if (block->getBlockDecl()->capturesVariable(Variable))
19301  Visit(block->getBlockDecl()->getBody());
19302  }
19303 
19304  void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
19305  if (Capturer) return;
19306  if (OVE->getSourceExpr())
19307  Visit(OVE->getSourceExpr());
19308  }
19309 
19310  void VisitBinaryOperator(BinaryOperator *BinOp) {
19311  if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
19312  return;
19313  Expr *LHS = BinOp->getLHS();
19314  if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
19315  if (DRE->getDecl() != Variable)
19316  return;
19317  if (Expr *RHS = BinOp->getRHS()) {
19318  RHS = RHS->IgnoreParenCasts();
19319  std::optional<llvm::APSInt> Value;
19320  VarWillBeReased =
19321  (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
19322  *Value == 0);
19323  }
19324  }
19325  }
19326  };
19327 
19328 } // namespace
19329 
19330 /// Check whether the given argument is a block which captures a
19331 /// variable.
19332 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
19333  assert(owner.Variable && owner.Loc.isValid());
19334 
19335  e = e->IgnoreParenCasts();
19336 
19337  // Look through [^{...} copy] and Block_copy(^{...}).
19338  if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
19339  Selector Cmd = ME->getSelector();
19340  if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
19341  e = ME->getInstanceReceiver();
19342  if (!e)
19343  return nullptr;
19344  e = e->IgnoreParenCasts();
19345  }
19346  } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
19347  if (CE->getNumArgs() == 1) {
19348  FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
19349  if (Fn) {
19350  const IdentifierInfo *FnI = Fn->getIdentifier();
19351  if (FnI && FnI->isStr("_Block_copy")) {
19352  e = CE->getArg(0)->IgnoreParenCasts();
19353  }
19354  }
19355  }
19356  }
19357 
19358  BlockExpr *block = dyn_cast<BlockExpr>(e);
19359  if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
19360  return nullptr;
19361 
19362  FindCaptureVisitor visitor(S.Context, owner.Variable);
19363  visitor.Visit(block->getBlockDecl()->getBody());
19364  return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
19365 }
19366 
19367 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
19368  RetainCycleOwner &owner) {
19369  assert(capturer);
19370  assert(owner.Variable && owner.Loc.isValid());
19371 
19372  S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
19373  << owner.Variable << capturer->getSourceRange();
19374  S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
19375  << owner.Indirect << owner.Range;
19376 }
19377 
19378 /// Check for a keyword selector that starts with the word 'add' or
19379 /// 'set'.
19380 static bool isSetterLikeSelector(Selector sel) {
19381  if (sel.isUnarySelector()) return false;
19382 
19383  StringRef str = sel.getNameForSlot(0);
19384  str = str.ltrim('_');
19385  if (str.starts_with("set"))
19386  str = str.substr(3);
19387  else if (str.starts_with("add")) {
19388  // Specially allow 'addOperationWithBlock:'.
19389  if (sel.getNumArgs() == 1 && str.starts_with("addOperationWithBlock"))
19390  return false;
19391  str = str.substr(3);
19392  } else
19393  return false;
19394 
19395  if (str.empty()) return true;
19396  return !isLowercase(str.front());
19397 }
19398 
19399 static std::optional<int>
19401  bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
19402  Message->getReceiverInterface(),
19404  if (!IsMutableArray) {
19405  return std::nullopt;
19406  }
19407 
19408  Selector Sel = Message->getSelector();
19409 
19410  std::optional<NSAPI::NSArrayMethodKind> MKOpt =
19411  S.NSAPIObj->getNSArrayMethodKind(Sel);
19412  if (!MKOpt) {
19413  return std::nullopt;
19414  }
19415 
19416  NSAPI::NSArrayMethodKind MK = *MKOpt;
19417 
19418  switch (MK) {
19422  return 0;
19424  return 1;
19425 
19426  default:
19427  return std::nullopt;
19428  }
19429 
19430  return std::nullopt;
19431 }
19432 
19433 static std::optional<int>
19435  bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
19436  Message->getReceiverInterface(),
19438  if (!IsMutableDictionary) {
19439  return std::nullopt;
19440  }
19441 
19442  Selector Sel = Message->getSelector();
19443 
19444  std::optional<NSAPI::NSDictionaryMethodKind> MKOpt =
19445  S.NSAPIObj->getNSDictionaryMethodKind(Sel);
19446  if (!MKOpt) {
19447  return std::nullopt;
19448  }
19449 
19450  NSAPI::NSDictionaryMethodKind MK = *MKOpt;
19451 
19452  switch (MK) {
19456  return 0;
19457 
19458  default:
19459  return std::nullopt;
19460  }
19461 
19462  return std::nullopt;
19463 }
19464 
19465 static std::optional<int> GetNSSetArgumentIndex(Sema &S,
19466  ObjCMessageExpr *Message) {
19467  bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
19468  Message->getReceiverInterface(),
19470 
19471  bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
19472  Message->getReceiverInterface(),
19474  if (!IsMutableSet && !IsMutableOrderedSet) {
19475  return std::nullopt;
19476  }
19477 
19478  Selector Sel = Message->getSelector();
19479 
19480  std::optional<NSAPI::NSSetMethodKind> MKOpt =
19481  S.NSAPIObj->getNSSetMethodKind(Sel);
19482  if (!MKOpt) {
19483  return std::nullopt;
19484  }
19485 
19486  NSAPI::NSSetMethodKind MK = *MKOpt;
19487 
19488  switch (MK) {
19493  return 0;
19495  return 1;
19496  }
19497 
19498  return std::nullopt;
19499 }
19500 
19501 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
19502  if (!Message->isInstanceMessage()) {
19503  return;
19504  }
19505 
19506  std::optional<int> ArgOpt;
19507 
19508  if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
19509  !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
19510  !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
19511  return;
19512  }
19513 
19514  int ArgIndex = *ArgOpt;
19515 
19516  Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
19517  if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
19518  Arg = OE->getSourceExpr()->IgnoreImpCasts();
19519  }
19520 
19521  if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
19522  if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
19523  if (ArgRE->isObjCSelfExpr()) {
19524  Diag(Message->getSourceRange().getBegin(),
19525  diag::warn_objc_circular_container)
19526  << ArgRE->getDecl() << StringRef("'super'");
19527  }
19528  }
19529  } else {
19530  Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
19531 
19532  if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
19533  Receiver = OE->getSourceExpr()->IgnoreImpCasts();
19534  }
19535 
19536  if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
19537  if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
19538  if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
19539  ValueDecl *Decl = ReceiverRE->getDecl();
19540  Diag(Message->getSourceRange().getBegin(),
19541  diag::warn_objc_circular_container)
19542  << Decl << Decl;
19543  if (!ArgRE->isObjCSelfExpr()) {
19544  Diag(Decl->getLocation(),
19545  diag::note_objc_circular_container_declared_here)
19546  << Decl;
19547  }
19548  }
19549  }
19550  } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
19551  if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
19552  if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
19553  ObjCIvarDecl *Decl = IvarRE->getDecl();
19554  Diag(Message->getSourceRange().getBegin(),
19555  diag::warn_objc_circular_container)
19556  << Decl << Decl;
19557  Diag(Decl->getLocation(),
19558  diag::note_objc_circular_container_declared_here)
19559  << Decl;
19560  }
19561  }
19562  }
19563  }
19564 }
19565 
19566 /// Check a message send to see if it's likely to cause a retain cycle.
19568  // Only check instance methods whose selector looks like a setter.
19569  if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
19570  return;
19571 
19572  // Try to find a variable that the receiver is strongly owned by.
19573  RetainCycleOwner owner;
19575  if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
19576  return;
19577  } else {
19579  owner.Variable = getCurMethodDecl()->getSelfDecl();
19580  owner.Loc = msg->getSuperLoc();
19581  owner.Range = msg->getSuperLoc();
19582  }
19583 
19584  // Check whether the receiver is captured by any of the arguments.
19585  const ObjCMethodDecl *MD = msg->getMethodDecl();
19586  for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
19587  if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
19588  // noescape blocks should not be retained by the method.
19589  if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
19590  continue;
19591  return diagnoseRetainCycle(*this, capturer, owner);
19592  }
19593  }
19594 }
19595 
19596 /// Check a property assign to see if it's likely to cause a retain cycle.
19597 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
19598  RetainCycleOwner owner;
19599  if (!findRetainCycleOwner(*this, receiver, owner))
19600  return;
19601 
19602  if (Expr *capturer = findCapturingExpr(*this, argument, owner))
19603  diagnoseRetainCycle(*this, capturer, owner);
19604 }
19605 
19607  RetainCycleOwner Owner;
19608  if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
19609  return;
19610 
19611  // Because we don't have an expression for the variable, we have to set the
19612  // location explicitly here.
19613  Owner.Loc = Var->getLocation();
19614  Owner.Range = Var->getSourceRange();
19615 
19616  if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
19617  diagnoseRetainCycle(*this, Capturer, Owner);
19618 }
19619 
19621  Expr *RHS, bool isProperty) {
19622  // Check if RHS is an Objective-C object literal, which also can get
19623  // immediately zapped in a weak reference. Note that we explicitly
19624  // allow ObjCStringLiterals, since those are designed to never really die.
19625  RHS = RHS->IgnoreParenImpCasts();
19626 
19627  // This enum needs to match with the 'select' in
19628  // warn_objc_arc_literal_assign (off-by-1).
19630  if (Kind == Sema::LK_String || Kind == Sema::LK_None)
19631  return false;
19632 
19633  S.Diag(Loc, diag::warn_arc_literal_assign)
19634  << (unsigned) Kind
19635  << (isProperty ? 0 : 1)
19636  << RHS->getSourceRange();
19637 
19638  return true;
19639 }
19640 
19643  Expr *RHS, bool isProperty) {
19644  // Strip off any implicit cast added to get to the one ARC-specific.
19645  while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
19646  if (cast->getCastKind() == CK_ARCConsumeObject) {
19647  S.Diag(Loc, diag::warn_arc_retained_assign)
19649  << (isProperty ? 0 : 1)
19650  << RHS->getSourceRange();
19651  return true;
19652  }
19653  RHS = cast->getSubExpr();
19654  }
19655 
19656  if (LT == Qualifiers::OCL_Weak &&
19657  checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
19658  return true;
19659 
19660  return false;
19661 }
19662 
19664  QualType LHS, Expr *RHS) {
19666 
19668  return false;
19669 
19670  if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
19671  return true;
19672 
19673  return false;
19674 }
19675 
19677  Expr *LHS, Expr *RHS) {
19678  QualType LHSType;
19679  // PropertyRef on LHS type need be directly obtained from
19680  // its declaration as it has a PseudoType.
19681  ObjCPropertyRefExpr *PRE
19682  = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
19683  if (PRE && !PRE->isImplicitProperty()) {
19684  const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
19685  if (PD)
19686  LHSType = PD->getType();
19687  }
19688 
19689  if (LHSType.isNull())
19690  LHSType = LHS->getType();
19691 
19693 
19694  if (LT == Qualifiers::OCL_Weak) {
19695  if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
19696  getCurFunction()->markSafeWeakUse(LHS);
19697  }
19698 
19699  if (checkUnsafeAssigns(Loc, LHSType, RHS))
19700  return;
19701 
19702  // FIXME. Check for other life times.
19703  if (LT != Qualifiers::OCL_None)
19704  return;
19705 
19706  if (PRE) {
19707  if (PRE->isImplicitProperty())
19708  return;
19709  const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
19710  if (!PD)
19711  return;
19712 
19713  unsigned Attributes = PD->getPropertyAttributes();
19714  if (Attributes & ObjCPropertyAttribute::kind_assign) {
19715  // when 'assign' attribute was not explicitly specified
19716  // by user, ignore it and rely on property type itself
19717  // for lifetime info.
19718  unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
19719  if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
19720  LHSType->isObjCRetainableType())
19721  return;
19722 
19723  while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
19724  if (cast->getCastKind() == CK_ARCConsumeObject) {
19725  Diag(Loc, diag::warn_arc_retained_property_assign)
19726  << RHS->getSourceRange();
19727  return;
19728  }
19729  RHS = cast->getSubExpr();
19730  }
19731  } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
19732  if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
19733  return;
19734  }
19735  }
19736 }
19737 
19738 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
19739 
19740 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
19741  SourceLocation StmtLoc,
19742  const NullStmt *Body) {
19743  // Do not warn if the body is a macro that expands to nothing, e.g:
19744  //
19745  // #define CALL(x)
19746  // if (condition)
19747  // CALL(0);
19748  if (Body->hasLeadingEmptyMacro())
19749  return false;
19750 
19751  // Get line numbers of statement and body.
19752  bool StmtLineInvalid;
19753  unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
19754  &StmtLineInvalid);
19755  if (StmtLineInvalid)
19756  return false;
19757 
19758  bool BodyLineInvalid;
19759  unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
19760  &BodyLineInvalid);
19761  if (BodyLineInvalid)
19762  return false;
19763 
19764  // Warn if null statement and body are on the same line.
19765  if (StmtLine != BodyLine)
19766  return false;
19767 
19768  return true;
19769 }
19770 
19772  const Stmt *Body,
19773  unsigned DiagID) {
19774  // Since this is a syntactic check, don't emit diagnostic for template
19775  // instantiations, this just adds noise.
19776  if (CurrentInstantiationScope)
19777  return;
19778 
19779  // The body should be a null statement.
19780  const NullStmt *NBody = dyn_cast<NullStmt>(Body);
19781  if (!NBody)
19782  return;
19783 
19784  // Do the usual checks.
19785  if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
19786  return;
19787 
19788  Diag(NBody->getSemiLoc(), DiagID);
19789  Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
19790 }
19791 
19793  const Stmt *PossibleBody) {
19794  assert(!CurrentInstantiationScope); // Ensured by caller
19795 
19796  SourceLocation StmtLoc;
19797  const Stmt *Body;
19798  unsigned DiagID;
19799  if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
19800  StmtLoc = FS->getRParenLoc();
19801  Body = FS->getBody();
19802  DiagID = diag::warn_empty_for_body;
19803  } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
19804  StmtLoc = WS->getRParenLoc();
19805  Body = WS->getBody();
19806  DiagID = diag::warn_empty_while_body;
19807  } else
19808  return; // Neither `for' nor `while'.
19809 
19810  // The body should be a null statement.
19811  const NullStmt *NBody = dyn_cast<NullStmt>(Body);
19812  if (!NBody)
19813  return;
19814 
19815  // Skip expensive checks if diagnostic is disabled.
19816  if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
19817  return;
19818 
19819  // Do the usual checks.
19820  if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
19821  return;
19822 
19823  // `for(...);' and `while(...);' are popular idioms, so in order to keep
19824  // noise level low, emit diagnostics only if for/while is followed by a
19825  // CompoundStmt, e.g.:
19826  // for (int i = 0; i < n; i++);
19827  // {
19828  // a(i);
19829  // }
19830  // or if for/while is followed by a statement with more indentation
19831  // than for/while itself:
19832  // for (int i = 0; i < n; i++);
19833  // a(i);
19834  bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
19835  if (!ProbableTypo) {
19836  bool BodyColInvalid;
19837  unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
19838  PossibleBody->getBeginLoc(), &BodyColInvalid);
19839  if (BodyColInvalid)
19840  return;
19841 
19842  bool StmtColInvalid;
19843  unsigned StmtCol =
19844  SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
19845  if (StmtColInvalid)
19846  return;
19847 
19848  if (BodyCol > StmtCol)
19849  ProbableTypo = true;
19850  }
19851 
19852  if (ProbableTypo) {
19853  Diag(NBody->getSemiLoc(), DiagID);
19854  Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
19855  }
19856 }
19857 
19858 //===--- CHECK: Warn on self move with std::move. -------------------------===//
19859 
19860 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
19861 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
19862  SourceLocation OpLoc) {
19863  if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
19864  return;
19865 
19866  if (inTemplateInstantiation())
19867  return;
19868 
19869  // Strip parens and casts away.
19870  LHSExpr = LHSExpr->IgnoreParenImpCasts();
19871  RHSExpr = RHSExpr->IgnoreParenImpCasts();
19872 
19873  // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
19874  // which we can treat as an inlined std::move
19875  if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
19876  CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
19877  RHSExpr = CE->getArg(0);
19878  else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
19879  CXXSCE && CXXSCE->isXValue())
19880  RHSExpr = CXXSCE->getSubExpr();
19881  else
19882  return;
19883 
19884  const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
19885  const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
19886 
19887  // Two DeclRefExpr's, check that the decls are the same.
19888  if (LHSDeclRef && RHSDeclRef) {
19889  if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
19890  return;
19891  if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
19892  RHSDeclRef->getDecl()->getCanonicalDecl())
19893  return;
19894 
19895  auto D = Diag(OpLoc, diag::warn_self_move)
19896  << LHSExpr->getType() << LHSExpr->getSourceRange()
19897  << RHSExpr->getSourceRange();
19898  if (const FieldDecl *F =
19899  getSelfAssignmentClassMemberCandidate(RHSDeclRef->getDecl()))
19900  D << 1 << F
19901  << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
19902  else
19903  D << 0;
19904  return;
19905  }
19906 
19907  // Member variables require a different approach to check for self moves.
19908  // MemberExpr's are the same if every nested MemberExpr refers to the same
19909  // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
19910  // the base Expr's are CXXThisExpr's.
19911  const Expr *LHSBase = LHSExpr;
19912  const Expr *RHSBase = RHSExpr;
19913  const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
19914  const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
19915  if (!LHSME || !RHSME)
19916  return;
19917 
19918  while (LHSME && RHSME) {
19919  if (LHSME->getMemberDecl()->getCanonicalDecl() !=
19920  RHSME->getMemberDecl()->getCanonicalDecl())
19921  return;
19922 
19923  LHSBase = LHSME->getBase();
19924  RHSBase = RHSME->getBase();
19925  LHSME = dyn_cast<MemberExpr>(LHSBase);
19926  RHSME = dyn_cast<MemberExpr>(RHSBase);
19927  }
19928 
19929  LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
19930  RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
19931  if (LHSDeclRef && RHSDeclRef) {
19932  if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
19933  return;
19934  if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
19935  RHSDeclRef->getDecl()->getCanonicalDecl())
19936  return;
19937 
19938  Diag(OpLoc, diag::warn_self_move)
19939  << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
19940  << RHSExpr->getSourceRange();
19941  return;
19942  }
19943 
19944  if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
19945  Diag(OpLoc, diag::warn_self_move)
19946  << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
19947  << RHSExpr->getSourceRange();
19948 }
19949 
19950 //===--- Layout compatibility ----------------------------------------------//
19951 
19952 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
19953 
19954 /// Check if two enumeration types are layout-compatible.
19955 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
19956  // C++11 [dcl.enum] p8:
19957  // Two enumeration types are layout-compatible if they have the same
19958  // underlying type.
19959  return ED1->isComplete() && ED2->isComplete() &&
19960  C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
19961 }
19962 
19963 /// Check if two fields are layout-compatible.
19964 /// Can be used on union members, which are exempt from alignment requirement
19965 /// of common initial sequence.
19966 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
19967  FieldDecl *Field2,
19968  bool AreUnionMembers = false) {
19969  [[maybe_unused]] const Type *Field1Parent =
19970  Field1->getParent()->getTypeForDecl();
19971  [[maybe_unused]] const Type *Field2Parent =
19972  Field2->getParent()->getTypeForDecl();
19973  assert(((Field1Parent->isStructureOrClassType() &&
19974  Field2Parent->isStructureOrClassType()) ||
19975  (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
19976  "Can't evaluate layout compatibility between a struct field and a "
19977  "union field.");
19978  assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
19979  (AreUnionMembers && Field1Parent->isUnionType())) &&
19980  "AreUnionMembers should be 'true' for union fields (only).");
19981 
19982  if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
19983  return false;
19984 
19985  if (Field1->isBitField() != Field2->isBitField())
19986  return false;
19987 
19988  if (Field1->isBitField()) {
19989  // Make sure that the bit-fields are the same length.
19990  unsigned Bits1 = Field1->getBitWidthValue(C);
19991  unsigned Bits2 = Field2->getBitWidthValue(C);
19992 
19993  if (Bits1 != Bits2)
19994  return false;
19995  }
19996 
19997  if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
19998  Field2->hasAttr<clang::NoUniqueAddressAttr>())
19999  return false;
20000 
20001  if (!AreUnionMembers &&
20002  Field1->getMaxAlignment() != Field2->getMaxAlignment())
20003  return false;
20004 
20005  return true;
20006 }
20007 
20008 /// Check if two standard-layout structs are layout-compatible.
20009 /// (C++11 [class.mem] p17)
20011  RecordDecl *RD2) {
20012  // If both records are C++ classes, check that base classes match.
20013  if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
20014  // If one of records is a CXXRecordDecl we are in C++ mode,
20015  // thus the other one is a CXXRecordDecl, too.
20016  const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
20017  // Check number of base classes.
20018  if (D1CXX->getNumBases() != D2CXX->getNumBases())
20019  return false;
20020 
20021  // Check the base classes.
20023  Base1 = D1CXX->bases_begin(),
20024  BaseEnd1 = D1CXX->bases_end(),
20025  Base2 = D2CXX->bases_begin();
20026  Base1 != BaseEnd1;
20027  ++Base1, ++Base2) {
20028  if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
20029  return false;
20030  }
20031  } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
20032  // If only RD2 is a C++ class, it should have zero base classes.
20033  if (D2CXX->getNumBases() > 0)
20034  return false;
20035  }
20036 
20037  // Check the fields.
20038  RecordDecl::field_iterator Field2 = RD2->field_begin(),
20039  Field2End = RD2->field_end(),
20040  Field1 = RD1->field_begin(),
20041  Field1End = RD1->field_end();
20042  for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
20043  if (!isLayoutCompatible(C, *Field1, *Field2))
20044  return false;
20045  }
20046  if (Field1 != Field1End || Field2 != Field2End)
20047  return false;
20048 
20049  return true;
20050 }
20051 
20052 /// Check if two standard-layout unions are layout-compatible.
20053 /// (C++11 [class.mem] p18)
20055  RecordDecl *RD2) {
20056  llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
20057  for (auto *Field2 : RD2->fields())
20058  UnmatchedFields.insert(Field2);
20059 
20060  for (auto *Field1 : RD1->fields()) {
20062  I = UnmatchedFields.begin(),
20063  E = UnmatchedFields.end();
20064 
20065  for ( ; I != E; ++I) {
20066  if (isLayoutCompatible(C, Field1, *I, /*IsUnionMember=*/true)) {
20067  bool Result = UnmatchedFields.erase(*I);
20068  (void) Result;
20069  assert(Result);
20070  break;
20071  }
20072  }
20073  if (I == E)
20074  return false;
20075  }
20076 
20077  return UnmatchedFields.empty();
20078 }
20079 
20081  RecordDecl *RD2) {
20082  if (RD1->isUnion() != RD2->isUnion())
20083  return false;
20084 
20085  if (RD1->isUnion())
20086  return isLayoutCompatibleUnion(C, RD1, RD2);
20087  else
20088  return isLayoutCompatibleStruct(C, RD1, RD2);
20089 }
20090 
20091 /// Check if two types are layout-compatible in C++11 sense.
20093  if (T1.isNull() || T2.isNull())
20094  return false;
20095 
20096  // C++20 [basic.types] p11:
20097  // Two types cv1 T1 and cv2 T2 are layout-compatible types
20098  // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
20099  // or layout-compatible standard-layout class types (11.4).
20102 
20103  if (C.hasSameType(T1, T2))
20104  return true;
20105 
20106  const Type::TypeClass TC1 = T1->getTypeClass();
20107  const Type::TypeClass TC2 = T2->getTypeClass();
20108 
20109  if (TC1 != TC2)
20110  return false;
20111 
20112  if (TC1 == Type::Enum) {
20113  return isLayoutCompatible(C,
20114  cast<EnumType>(T1)->getDecl(),
20115  cast<EnumType>(T2)->getDecl());
20116  } else if (TC1 == Type::Record) {
20117  if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
20118  return false;
20119 
20120  return isLayoutCompatible(C,
20121  cast<RecordType>(T1)->getDecl(),
20122  cast<RecordType>(T2)->getDecl());
20123  }
20124 
20125  return false;
20126 }
20127 
20129  return isLayoutCompatible(getASTContext(), T1, T2);
20130 }
20131 
20132 //===-------------- Pointer interconvertibility ----------------------------//
20133 
20135  const TypeSourceInfo *Derived) {
20136  QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
20137  QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
20138 
20139  if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
20140  getASTContext().hasSameType(BaseT, DerivedT))
20141  return true;
20142 
20143  if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
20144  return false;
20145 
20146  // Per [basic.compound]/4.3, containing object has to be standard-layout.
20147  if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
20148  return true;
20149 
20150  return false;
20151 }
20152 
20153 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
20154 
20155 /// Given a type tag expression find the type tag itself.
20156 ///
20157 /// \param TypeExpr Type tag expression, as it appears in user's code.
20158 ///
20159 /// \param VD Declaration of an identifier that appears in a type tag.
20160 ///
20161 /// \param MagicValue Type tag magic value.
20162 ///
20163 /// \param isConstantEvaluated whether the evalaution should be performed in
20164 
20165 /// constant context.
20166 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
20167  const ValueDecl **VD, uint64_t *MagicValue,
20168  bool isConstantEvaluated) {
20169  while(true) {
20170  if (!TypeExpr)
20171  return false;
20172 
20173  TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
20174 
20175  switch (TypeExpr->getStmtClass()) {
20176  case Stmt::UnaryOperatorClass: {
20177  const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
20178  if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
20179  TypeExpr = UO->getSubExpr();
20180  continue;
20181  }
20182  return false;
20183  }
20184 
20185  case Stmt::DeclRefExprClass: {
20186  const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
20187  *VD = DRE->getDecl();
20188  return true;
20189  }
20190 
20191  case Stmt::IntegerLiteralClass: {
20192  const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
20193  llvm::APInt MagicValueAPInt = IL->getValue();
20194  if (MagicValueAPInt.getActiveBits() <= 64) {
20195  *MagicValue = MagicValueAPInt.getZExtValue();
20196  return true;
20197  } else
20198  return false;
20199  }
20200 
20201  case Stmt::BinaryConditionalOperatorClass:
20202  case Stmt::ConditionalOperatorClass: {
20203  const AbstractConditionalOperator *ACO =
20204  cast<AbstractConditionalOperator>(TypeExpr);
20205  bool Result;
20206  if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
20207  isConstantEvaluated)) {
20208  if (Result)
20209  TypeExpr = ACO->getTrueExpr();
20210  else
20211  TypeExpr = ACO->getFalseExpr();
20212  continue;
20213  }
20214  return false;
20215  }
20216 
20217  case Stmt::BinaryOperatorClass: {
20218  const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
20219  if (BO->getOpcode() == BO_Comma) {
20220  TypeExpr = BO->getRHS();
20221  continue;
20222  }
20223  return false;
20224  }
20225 
20226  default:
20227  return false;
20228  }
20229  }
20230 }
20231 
20232 /// Retrieve the C type corresponding to type tag TypeExpr.
20233 ///
20234 /// \param TypeExpr Expression that specifies a type tag.
20235 ///
20236 /// \param MagicValues Registered magic values.
20237 ///
20238 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
20239 /// kind.
20240 ///
20241 /// \param TypeInfo Information about the corresponding C type.
20242 ///
20243 /// \param isConstantEvaluated whether the evalaution should be performed in
20244 /// constant context.
20245 ///
20246 /// \returns true if the corresponding C type was found.
20247 static bool GetMatchingCType(
20248  const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
20249  const ASTContext &Ctx,
20250  const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
20251  *MagicValues,
20252  bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
20253  bool isConstantEvaluated) {
20254  FoundWrongKind = false;
20255 
20256  // Variable declaration that has type_tag_for_datatype attribute.
20257  const ValueDecl *VD = nullptr;
20258 
20259  uint64_t MagicValue;
20260 
20261  if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
20262  return false;
20263 
20264  if (VD) {
20265  if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
20266  if (I->getArgumentKind() != ArgumentKind) {
20267  FoundWrongKind = true;
20268  return false;
20269  }
20270  TypeInfo.Type = I->getMatchingCType();
20271  TypeInfo.LayoutCompatible = I->getLayoutCompatible();
20272  TypeInfo.MustBeNull = I->getMustBeNull();
20273  return true;
20274  }
20275  return false;
20276  }
20277 
20278  if (!MagicValues)
20279  return false;
20280 
20281  llvm::DenseMap<Sema::TypeTagMagicValue,
20282  Sema::TypeTagData>::const_iterator I =
20283  MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
20284  if (I == MagicValues->end())
20285  return false;
20286 
20287  TypeInfo = I->second;
20288  return true;
20289 }
20290 
20292  uint64_t MagicValue, QualType Type,
20293  bool LayoutCompatible,
20294  bool MustBeNull) {
20295  if (!TypeTagForDatatypeMagicValues)
20296  TypeTagForDatatypeMagicValues.reset(
20297  new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
20298 
20299  TypeTagMagicValue Magic(ArgumentKind, MagicValue);
20300  (*TypeTagForDatatypeMagicValues)[Magic] =
20301  TypeTagData(Type, LayoutCompatible, MustBeNull);
20302 }
20303 
20304 static bool IsSameCharType(QualType T1, QualType T2) {
20305  const BuiltinType *BT1 = T1->getAs<BuiltinType>();
20306  if (!BT1)
20307  return false;
20308 
20309  const BuiltinType *BT2 = T2->getAs<BuiltinType>();
20310  if (!BT2)
20311  return false;
20312 
20313  BuiltinType::Kind T1Kind = BT1->getKind();
20314  BuiltinType::Kind T2Kind = BT2->getKind();
20315 
20316  return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
20317  (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
20318  (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
20319  (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
20320 }
20321 
20322 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
20323  const ArrayRef<const Expr *> ExprArgs,
20324  SourceLocation CallSiteLoc) {
20325  const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
20326  bool IsPointerAttr = Attr->getIsPointer();
20327 
20328  // Retrieve the argument representing the 'type_tag'.
20329  unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
20330  if (TypeTagIdxAST >= ExprArgs.size()) {
20331  Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
20332  << 0 << Attr->getTypeTagIdx().getSourceIndex();
20333  return;
20334  }
20335  const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
20336  bool FoundWrongKind;
20337  TypeTagData TypeInfo;
20338  if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
20339  TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
20340  TypeInfo, isConstantEvaluatedContext())) {
20341  if (FoundWrongKind)
20342  Diag(TypeTagExpr->getExprLoc(),
20343  diag::warn_type_tag_for_datatype_wrong_kind)
20344  << TypeTagExpr->getSourceRange();
20345  return;
20346  }
20347 
20348  // Retrieve the argument representing the 'arg_idx'.
20349  unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
20350  if (ArgumentIdxAST >= ExprArgs.size()) {
20351  Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
20352  << 1 << Attr->getArgumentIdx().getSourceIndex();
20353  return;
20354  }
20355  const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
20356  if (IsPointerAttr) {
20357  // Skip implicit cast of pointer to `void *' (as a function argument).
20358  if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
20359  if (ICE->getType()->isVoidPointerType() &&
20360  ICE->getCastKind() == CK_BitCast)
20361  ArgumentExpr = ICE->getSubExpr();
20362  }
20363  QualType ArgumentType = ArgumentExpr->getType();
20364 
20365  // Passing a `void*' pointer shouldn't trigger a warning.
20366  if (IsPointerAttr && ArgumentType->isVoidPointerType())
20367  return;
20368 
20369  if (TypeInfo.MustBeNull) {
20370  // Type tag with matching void type requires a null pointer.
20371  if (!ArgumentExpr->isNullPointerConstant(Context,
20373  Diag(ArgumentExpr->getExprLoc(),
20374  diag::warn_type_safety_null_pointer_required)
20375  << ArgumentKind->getName()
20376  << ArgumentExpr->getSourceRange()
20377  << TypeTagExpr->getSourceRange();
20378  }
20379  return;
20380  }
20381 
20382  QualType RequiredType = TypeInfo.Type;
20383  if (IsPointerAttr)
20384  RequiredType = Context.getPointerType(RequiredType);
20385 
20386  bool mismatch = false;
20387  if (!TypeInfo.LayoutCompatible) {
20388  mismatch = !Context.hasSameType(ArgumentType, RequiredType);
20389 
20390  // C++11 [basic.fundamental] p1:
20391  // Plain char, signed char, and unsigned char are three distinct types.
20392  //
20393  // But we treat plain `char' as equivalent to `signed char' or `unsigned
20394  // char' depending on the current char signedness mode.
20395  if (mismatch)
20396  if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
20397  RequiredType->getPointeeType())) ||
20398  (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
20399  mismatch = false;
20400  } else
20401  if (IsPointerAttr)
20402  mismatch = !isLayoutCompatible(Context,
20403  ArgumentType->getPointeeType(),
20404  RequiredType->getPointeeType());
20405  else
20406  mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
20407 
20408  if (mismatch)
20409  Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
20410  << ArgumentType << ArgumentKind
20411  << TypeInfo.LayoutCompatible << RequiredType
20412  << ArgumentExpr->getSourceRange()
20413  << TypeTagExpr->getSourceRange();
20414 }
20415 
20416 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
20417  CharUnits Alignment) {
20418  MisalignedMembers.emplace_back(E, RD, MD, Alignment);
20419 }
20420 
20422  for (MisalignedMember &m : MisalignedMembers) {
20423  const NamedDecl *ND = m.RD;
20424  if (ND->getName().empty()) {
20425  if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
20426  ND = TD;
20427  }
20428  Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
20429  << m.MD << ND << m.E->getSourceRange();
20430  }
20431  MisalignedMembers.clear();
20432 }
20433 
20435  E = E->IgnoreParens();
20436  if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
20437  return;
20438  if (isa<UnaryOperator>(E) &&
20439  cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
20440  auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
20441  if (isa<MemberExpr>(Op)) {
20442  auto *MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
20443  if (MA != MisalignedMembers.end() &&
20444  (T->isDependentType() || T->isIntegerType() ||
20446  Context.getTypeAlignInChars(
20447  T->getPointeeType()) <= MA->Alignment))))
20448  MisalignedMembers.erase(MA);
20449  }
20450  }
20451 }
20452 
20454  Expr *E,
20455  llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
20456  Action) {
20457  const auto *ME = dyn_cast<MemberExpr>(E);
20458  if (!ME)
20459  return;
20460 
20461  // No need to check expressions with an __unaligned-qualified type.
20462  if (E->getType().getQualifiers().hasUnaligned())
20463  return;
20464 
20465  // For a chain of MemberExpr like "a.b.c.d" this list
20466  // will keep FieldDecl's like [d, c, b].
20467  SmallVector<FieldDecl *, 4> ReverseMemberChain;
20468  const MemberExpr *TopME = nullptr;
20469  bool AnyIsPacked = false;
20470  do {
20471  QualType BaseType = ME->getBase()->getType();
20472  if (BaseType->isDependentType())
20473  return;
20474  if (ME->isArrow())
20475  BaseType = BaseType->getPointeeType();
20476  RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
20477  if (RD->isInvalidDecl())
20478  return;
20479 
20480  ValueDecl *MD = ME->getMemberDecl();
20481  auto *FD = dyn_cast<FieldDecl>(MD);
20482  // We do not care about non-data members.
20483  if (!FD || FD->isInvalidDecl())
20484  return;
20485 
20486  AnyIsPacked =
20487  AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
20488  ReverseMemberChain.push_back(FD);
20489 
20490  TopME = ME;
20491  ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
20492  } while (ME);
20493  assert(TopME && "We did not compute a topmost MemberExpr!");
20494 
20495  // Not the scope of this diagnostic.
20496  if (!AnyIsPacked)
20497  return;
20498 
20499  const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
20500  const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
20501  // TODO: The innermost base of the member expression may be too complicated.
20502  // For now, just disregard these cases. This is left for future
20503  // improvement.
20504  if (!DRE && !isa<CXXThisExpr>(TopBase))
20505  return;
20506 
20507  // Alignment expected by the whole expression.
20508  CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
20509 
20510  // No need to do anything else with this case.
20511  if (ExpectedAlignment.isOne())
20512  return;
20513 
20514  // Synthesize offset of the whole access.
20515  CharUnits Offset;
20516  for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
20517  Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
20518 
20519  // Compute the CompleteObjectAlignment as the alignment of the whole chain.
20520  CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
20521  ReverseMemberChain.back()->getParent()->getTypeForDecl());
20522 
20523  // The base expression of the innermost MemberExpr may give
20524  // stronger guarantees than the class containing the member.
20525  if (DRE && !TopME->isArrow()) {
20526  const ValueDecl *VD = DRE->getDecl();
20527  if (!VD->getType()->isReferenceType())
20528  CompleteObjectAlignment =
20529  std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
20530  }
20531 
20532  // Check if the synthesized offset fulfills the alignment.
20533  if (Offset % ExpectedAlignment != 0 ||
20534  // It may fulfill the offset it but the effective alignment may still be
20535  // lower than the expected expression alignment.
20536  CompleteObjectAlignment < ExpectedAlignment) {
20537  // If this happens, we want to determine a sensible culprit of this.
20538  // Intuitively, watching the chain of member expressions from right to
20539  // left, we start with the required alignment (as required by the field
20540  // type) but some packed attribute in that chain has reduced the alignment.
20541  // It may happen that another packed structure increases it again. But if
20542  // we are here such increase has not been enough. So pointing the first
20543  // FieldDecl that either is packed or else its RecordDecl is,
20544  // seems reasonable.
20545  FieldDecl *FD = nullptr;
20546  CharUnits Alignment;
20547  for (FieldDecl *FDI : ReverseMemberChain) {
20548  if (FDI->hasAttr<PackedAttr>() ||
20549  FDI->getParent()->hasAttr<PackedAttr>()) {
20550  FD = FDI;
20551  Alignment = std::min(
20552  Context.getTypeAlignInChars(FD->getType()),
20553  Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
20554  break;
20555  }
20556  }
20557  assert(FD && "We did not find a packed FieldDecl!");
20558  Action(E, FD->getParent(), FD, Alignment);
20559  }
20560 }
20561 
20562 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
20563  using namespace std::placeholders;
20564 
20565  RefersToMemberWithReducedAlignment(
20566  rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
20567  _2, _3, _4));
20568 }
20569 
20570 bool Sema::PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall) {
20571  if (checkArgCount(*this, TheCall, 1))
20572  return true;
20573 
20574  ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
20575  if (A.isInvalid())
20576  return true;
20577 
20578  TheCall->setArg(0, A.get());
20579  QualType TyA = A.get()->getType();
20580 
20581  if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA, 1))
20582  return true;
20583 
20584  TheCall->setType(TyA);
20585  return false;
20586 }
20587 
20588 bool Sema::BuiltinElementwiseMath(CallExpr *TheCall) {
20589  QualType Res;
20590  if (BuiltinVectorMath(TheCall, Res))
20591  return true;
20592  TheCall->setType(Res);
20593  return false;
20594 }
20595 
20597  QualType Res;
20598  if (BuiltinVectorMath(TheCall, Res))
20599  return true;
20600 
20601  if (auto *VecTy0 = Res->getAs<VectorType>())
20602  TheCall->setType(VecTy0->getElementType());
20603  else
20604  TheCall->setType(Res);
20605 
20606  return false;
20607 }
20608 
20610  if (checkArgCount(*this, TheCall, 2))
20611  return true;
20612 
20613  ExprResult A = TheCall->getArg(0);
20614  ExprResult B = TheCall->getArg(1);
20615  // Do standard promotions between the two arguments, returning their common
20616  // type.
20617  Res = UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);
20618  if (A.isInvalid() || B.isInvalid())
20619  return true;
20620 
20621  QualType TyA = A.get()->getType();
20622  QualType TyB = B.get()->getType();
20623 
20624  if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())
20625  return Diag(A.get()->getBeginLoc(),
20626  diag::err_typecheck_call_different_arg_types)
20627  << TyA << TyB;
20628 
20629  if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA, 1))
20630  return true;
20631 
20632  TheCall->setArg(0, A.get());
20633  TheCall->setArg(1, B.get());
20634  return false;
20635 }
20636 
20637 bool Sema::BuiltinElementwiseTernaryMath(CallExpr *TheCall,
20638  bool CheckForFloatArgs) {
20639  if (checkArgCount(*this, TheCall, 3))
20640  return true;
20641 
20642  Expr *Args[3];
20643  for (int I = 0; I < 3; ++I) {
20644  ExprResult Converted = UsualUnaryConversions(TheCall->getArg(I));
20645  if (Converted.isInvalid())
20646  return true;
20647  Args[I] = Converted.get();
20648  }
20649 
20650  if (CheckForFloatArgs) {
20651  int ArgOrdinal = 1;
20652  for (Expr *Arg : Args) {
20653  if (checkFPMathBuiltinElementType(*this, Arg->getBeginLoc(),
20654  Arg->getType(), ArgOrdinal++))
20655  return true;
20656  }
20657  } else {
20658  int ArgOrdinal = 1;
20659  for (Expr *Arg : Args) {
20660  if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
20661  ArgOrdinal++))
20662  return true;
20663  }
20664  }
20665 
20666  for (int I = 1; I < 3; ++I) {
20667  if (Args[0]->getType().getCanonicalType() !=
20668  Args[I]->getType().getCanonicalType()) {
20669  return Diag(Args[0]->getBeginLoc(),
20670  diag::err_typecheck_call_different_arg_types)
20671  << Args[0]->getType() << Args[I]->getType();
20672  }
20673 
20674  TheCall->setArg(I, Args[I]);
20675  }
20676 
20677  TheCall->setType(Args[0]->getType());
20678  return false;
20679 }
20680 
20681 bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
20682  if (checkArgCount(*this, TheCall, 1))
20683  return true;
20684 
20685  ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
20686  if (A.isInvalid())
20687  return true;
20688 
20689  TheCall->setArg(0, A.get());
20690  return false;
20691 }
20692 
20693 bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
20694  if (checkArgCount(*this, TheCall, 1))
20695  return true;
20696 
20697  ExprResult Arg = TheCall->getArg(0);
20698  QualType TyArg = Arg.get()->getType();
20699 
20700  if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
20701  return Diag(TheCall->getArg(0)->getBeginLoc(), diag::err_builtin_invalid_arg_type)
20702  << 1 << /*vector, integer or floating point ty*/ 0 << TyArg;
20703 
20704  TheCall->setType(TyArg);
20705  return false;
20706 }
20707 
20708 ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
20709  ExprResult CallResult) {
20710  if (checkArgCount(*this, TheCall, 1))
20711  return ExprError();
20712 
20713  ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
20714  if (MatrixArg.isInvalid())
20715  return MatrixArg;
20716  Expr *Matrix = MatrixArg.get();
20717 
20718  auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
20719  if (!MType) {
20720  Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
20721  << 1 << /* matrix ty*/ 1 << Matrix->getType();
20722  return ExprError();
20723  }
20724 
20725  // Create returned matrix type by swapping rows and columns of the argument
20726  // matrix type.
20727  QualType ResultType = Context.getConstantMatrixType(
20728  MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
20729 
20730  // Change the return type to the type of the returned matrix.
20731  TheCall->setType(ResultType);
20732 
20733  // Update call argument to use the possibly converted matrix argument.
20734  TheCall->setArg(0, Matrix);
20735  return CallResult;
20736 }
20737 
20738 // Get and verify the matrix dimensions.
20739 static std::optional<unsigned>
20741  SourceLocation ErrorPos;
20742  std::optional<llvm::APSInt> Value =
20743  Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
20744  if (!Value) {
20745  S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
20746  << Name;
20747  return {};
20748  }
20749  uint64_t Dim = Value->getZExtValue();
20751  S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
20753  return {};
20754  }
20755  return Dim;
20756 }
20757 
20758 ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
20759  ExprResult CallResult) {
20760  if (!getLangOpts().MatrixTypes) {
20761  Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
20762  return ExprError();
20763  }
20764 
20765  if (checkArgCount(*this, TheCall, 4))
20766  return ExprError();
20767 
20768  unsigned PtrArgIdx = 0;
20769  Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
20770  Expr *RowsExpr = TheCall->getArg(1);
20771  Expr *ColumnsExpr = TheCall->getArg(2);
20772  Expr *StrideExpr = TheCall->getArg(3);
20773 
20774  bool ArgError = false;
20775 
20776  // Check pointer argument.
20777  {
20778  ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
20779  if (PtrConv.isInvalid())
20780  return PtrConv;
20781  PtrExpr = PtrConv.get();
20782  TheCall->setArg(0, PtrExpr);
20783  if (PtrExpr->isTypeDependent()) {
20784  TheCall->setType(Context.DependentTy);
20785  return TheCall;
20786  }
20787  }
20788 
20789  auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
20790  QualType ElementTy;
20791  if (!PtrTy) {
20792  Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
20793  << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
20794  ArgError = true;
20795  } else {
20796  ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
20797 
20798  if (!ConstantMatrixType::isValidElementType(ElementTy)) {
20799  Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
20800  << PtrArgIdx + 1 << /* pointer to element ty*/ 2
20801  << PtrExpr->getType();
20802  ArgError = true;
20803  }
20804  }
20805 
20806  // Apply default Lvalue conversions and convert the expression to size_t.
20807  auto ApplyArgumentConversions = [this](Expr *E) {
20808  ExprResult Conv = DefaultLvalueConversion(E);
20809  if (Conv.isInvalid())
20810  return Conv;
20811 
20812  return tryConvertExprToType(Conv.get(), Context.getSizeType());
20813  };
20814 
20815  // Apply conversion to row and column expressions.
20816  ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
20817  if (!RowsConv.isInvalid()) {
20818  RowsExpr = RowsConv.get();
20819  TheCall->setArg(1, RowsExpr);
20820  } else
20821  RowsExpr = nullptr;
20822 
20823  ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
20824  if (!ColumnsConv.isInvalid()) {
20825  ColumnsExpr = ColumnsConv.get();
20826  TheCall->setArg(2, ColumnsExpr);
20827  } else
20828  ColumnsExpr = nullptr;
20829 
20830  // If any part of the result matrix type is still pending, just use
20831  // Context.DependentTy, until all parts are resolved.
20832  if ((RowsExpr && RowsExpr->isTypeDependent()) ||
20833  (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
20834  TheCall->setType(Context.DependentTy);
20835  return CallResult;
20836  }
20837 
20838  // Check row and column dimensions.
20839  std::optional<unsigned> MaybeRows;
20840  if (RowsExpr)
20841  MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
20842 
20843  std::optional<unsigned> MaybeColumns;
20844  if (ColumnsExpr)
20845  MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
20846 
20847  // Check stride argument.
20848  ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
20849  if (StrideConv.isInvalid())
20850  return ExprError();
20851  StrideExpr = StrideConv.get();
20852  TheCall->setArg(3, StrideExpr);
20853 
20854  if (MaybeRows) {
20855  if (std::optional<llvm::APSInt> Value =
20856  StrideExpr->getIntegerConstantExpr(Context)) {
20857  uint64_t Stride = Value->getZExtValue();
20858  if (Stride < *MaybeRows) {
20859  Diag(StrideExpr->getBeginLoc(),
20860  diag::err_builtin_matrix_stride_too_small);
20861  ArgError = true;
20862  }
20863  }
20864  }
20865 
20866  if (ArgError || !MaybeRows || !MaybeColumns)
20867  return ExprError();
20868 
20869  TheCall->setType(
20870  Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
20871  return CallResult;
20872 }
20873 
20874 ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
20875  ExprResult CallResult) {
20876  if (checkArgCount(*this, TheCall, 3))
20877  return ExprError();
20878 
20879  unsigned PtrArgIdx = 1;
20880  Expr *MatrixExpr = TheCall->getArg(0);
20881  Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
20882  Expr *StrideExpr = TheCall->getArg(2);
20883 
20884  bool ArgError = false;
20885 
20886  {
20887  ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
20888  if (MatrixConv.isInvalid())
20889  return MatrixConv;
20890  MatrixExpr = MatrixConv.get();
20891  TheCall->setArg(0, MatrixExpr);
20892  }
20893  if (MatrixExpr->isTypeDependent()) {
20894  TheCall->setType(Context.DependentTy);
20895  return TheCall;
20896  }
20897 
20898  auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
20899  if (!MatrixTy) {
20900  Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
20901  << 1 << /*matrix ty */ 1 << MatrixExpr->getType();
20902  ArgError = true;
20903  }
20904 
20905  {
20906  ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
20907  if (PtrConv.isInvalid())
20908  return PtrConv;
20909  PtrExpr = PtrConv.get();
20910  TheCall->setArg(1, PtrExpr);
20911  if (PtrExpr->isTypeDependent()) {
20912  TheCall->setType(Context.DependentTy);
20913  return TheCall;
20914  }
20915  }
20916 
20917  // Check pointer argument.
20918  auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
20919  if (!PtrTy) {
20920  Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
20921  << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
20922  ArgError = true;
20923  } else {
20924  QualType ElementTy = PtrTy->getPointeeType();
20925  if (ElementTy.isConstQualified()) {
20926  Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
20927  ArgError = true;
20928  }
20929  ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
20930  if (MatrixTy &&
20931  !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
20932  Diag(PtrExpr->getBeginLoc(),
20933  diag::err_builtin_matrix_pointer_arg_mismatch)
20934  << ElementTy << MatrixTy->getElementType();
20935  ArgError = true;
20936  }
20937  }
20938 
20939  // Apply default Lvalue conversions and convert the stride expression to
20940  // size_t.
20941  {
20942  ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
20943  if (StrideConv.isInvalid())
20944  return StrideConv;
20945 
20946  StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
20947  if (StrideConv.isInvalid())
20948  return StrideConv;
20949  StrideExpr = StrideConv.get();
20950  TheCall->setArg(2, StrideExpr);
20951  }
20952 
20953  // Check stride argument.
20954  if (MatrixTy) {
20955  if (std::optional<llvm::APSInt> Value =
20956  StrideExpr->getIntegerConstantExpr(Context)) {
20957  uint64_t Stride = Value->getZExtValue();
20958  if (Stride < MatrixTy->getNumRows()) {
20959  Diag(StrideExpr->getBeginLoc(),
20960  diag::err_builtin_matrix_stride_too_small);
20961  ArgError = true;
20962  }
20963  }
20964  }
20965 
20966  if (ArgError)
20967  return ExprError();
20968 
20969  return CallResult;
20970 }
20971 
20972 /// Checks the argument at the given index is a WebAssembly table and if it
20973 /// is, sets ElTy to the element type.
20974 static bool CheckWasmBuiltinArgIsTable(Sema &S, CallExpr *E, unsigned ArgIndex,
20975  QualType &ElTy) {
20976  Expr *ArgExpr = E->getArg(ArgIndex);
20977  const auto *ATy = dyn_cast<ArrayType>(ArgExpr->getType());
20978  if (!ATy || !ATy->getElementType().isWebAssemblyReferenceType()) {
20979  return S.Diag(ArgExpr->getBeginLoc(),
20980  diag::err_wasm_builtin_arg_must_be_table_type)
20981  << ArgIndex + 1 << ArgExpr->getSourceRange();
20982  }
20983  ElTy = ATy->getElementType();
20984  return false;
20985 }
20986 
20987 /// Checks the argument at the given index is an integer.
20989  unsigned ArgIndex) {
20990  Expr *ArgExpr = E->getArg(ArgIndex);
20991  if (!ArgExpr->getType()->isIntegerType()) {
20992  return S.Diag(ArgExpr->getBeginLoc(),
20993  diag::err_wasm_builtin_arg_must_be_integer_type)
20994  << ArgIndex + 1 << ArgExpr->getSourceRange();
20995  }
20996  return false;
20997 }
20998 
20999 /// Check that the first argument is a WebAssembly table, and the second
21000 /// is an index to use as index into the table.
21001 bool Sema::BuiltinWasmTableGet(CallExpr *TheCall) {
21002  if (checkArgCount(*this, TheCall, 2))
21003  return true;
21004 
21005  QualType ElTy;
21006  if (CheckWasmBuiltinArgIsTable(*this, TheCall, 0, ElTy))
21007  return true;
21008 
21009  if (CheckWasmBuiltinArgIsInteger(*this, TheCall, 1))
21010  return true;
21011 
21012  // If all is well, we set the type of TheCall to be the type of the
21013  // element of the table.
21014  // i.e. a table.get on an externref table has type externref,
21015  // or whatever the type of the table element is.
21016  TheCall->setType(ElTy);
21017 
21018  return false;
21019 }
21020 
21021 /// Check that the first argumnet is a WebAssembly table, the second is
21022 /// an index to use as index into the table and the third is the reference
21023 /// type to set into the table.
21024 bool Sema::BuiltinWasmTableSet(CallExpr *TheCall) {
21025  if (checkArgCount(*this, TheCall, 3))
21026  return true;
21027 
21028  QualType ElTy;
21029  if (CheckWasmBuiltinArgIsTable(*this, TheCall, 0, ElTy))
21030  return true;
21031 
21032  if (CheckWasmBuiltinArgIsInteger(*this, TheCall, 1))
21033  return true;
21034 
21035  if (!Context.hasSameType(ElTy, TheCall->getArg(2)->getType()))
21036  return true;
21037 
21038  return false;
21039 }
21040 
21041 /// Check that the argument is a WebAssembly table.
21042 bool Sema::BuiltinWasmTableSize(CallExpr *TheCall) {
21043  if (checkArgCount(*this, TheCall, 1))
21044  return true;
21045 
21046  QualType ElTy;
21047  if (CheckWasmBuiltinArgIsTable(*this, TheCall, 0, ElTy))
21048  return true;
21049 
21050  return false;
21051 }
21052 
21053 /// Check that the first argument is a WebAssembly table, the second is the
21054 /// value to use for new elements (of a type matching the table type), the
21055 /// third value is an integer.
21056 bool Sema::BuiltinWasmTableGrow(CallExpr *TheCall) {
21057  if (checkArgCount(*this, TheCall, 3))
21058  return true;
21059 
21060  QualType ElTy;
21061  if (CheckWasmBuiltinArgIsTable(*this, TheCall, 0, ElTy))
21062  return true;
21063 
21064  Expr *NewElemArg = TheCall->getArg(1);
21065  if (!Context.hasSameType(ElTy, NewElemArg->getType())) {
21066  return Diag(NewElemArg->getBeginLoc(),
21067  diag::err_wasm_builtin_arg_must_match_table_element_type)
21068  << 2 << 1 << NewElemArg->getSourceRange();
21069  }
21070 
21071  if (CheckWasmBuiltinArgIsInteger(*this, TheCall, 2))
21072  return true;
21073 
21074  return false;
21075 }
21076 
21077 /// Check that the first argument is a WebAssembly table, the second is an
21078 /// integer, the third is the value to use to fill the table (of a type
21079 /// matching the table type), and the fourth is an integer.
21080 bool Sema::BuiltinWasmTableFill(CallExpr *TheCall) {
21081  if (checkArgCount(*this, TheCall, 4))
21082  return true;
21083 
21084  QualType ElTy;
21085  if (CheckWasmBuiltinArgIsTable(*this, TheCall, 0, ElTy))
21086  return true;
21087 
21088  if (CheckWasmBuiltinArgIsInteger(*this, TheCall, 1))
21089  return true;
21090 
21091  Expr *NewElemArg = TheCall->getArg(2);
21092  if (!Context.hasSameType(ElTy, NewElemArg->getType())) {
21093  return Diag(NewElemArg->getBeginLoc(),
21094  diag::err_wasm_builtin_arg_must_match_table_element_type)
21095  << 3 << 1 << NewElemArg->getSourceRange();
21096  }
21097 
21098  if (CheckWasmBuiltinArgIsInteger(*this, TheCall, 3))
21099  return true;
21100 
21101  return false;
21102 }
21103 
21104 /// Check that the first argument is a WebAssembly table, the second is also a
21105 /// WebAssembly table (of the same element type), and the third to fifth
21106 /// arguments are integers.
21107 bool Sema::BuiltinWasmTableCopy(CallExpr *TheCall) {
21108  if (checkArgCount(*this, TheCall, 5))
21109  return true;
21110 
21111  QualType XElTy;
21112  if (CheckWasmBuiltinArgIsTable(*this, TheCall, 0, XElTy))
21113  return true;
21114 
21115  QualType YElTy;
21116  if (CheckWasmBuiltinArgIsTable(*this, TheCall, 1, YElTy))
21117  return true;
21118 
21119  Expr *TableYArg = TheCall->getArg(1);
21120  if (!Context.hasSameType(XElTy, YElTy)) {
21121  return Diag(TableYArg->getBeginLoc(),
21122  diag::err_wasm_builtin_arg_must_match_table_element_type)
21123  << 2 << 1 << TableYArg->getSourceRange();
21124  }
21125 
21126  for (int I = 2; I <= 4; I++) {
21127  if (CheckWasmBuiltinArgIsInteger(*this, TheCall, I))
21128  return true;
21129  }
21130 
21131  return false;
21132 }
21133 
21134 /// \brief Enforce the bounds of a TCB
21135 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
21136 /// directly calls other functions in the same TCB as marked by the enforce_tcb
21137 /// and enforce_tcb_leaf attributes.
21138 void Sema::CheckTCBEnforcement(const SourceLocation CallExprLoc,
21139  const NamedDecl *Callee) {
21140  // This warning does not make sense in code that has no runtime behavior.
21141  if (isUnevaluatedContext())
21142  return;
21143 
21144  const NamedDecl *Caller = getCurFunctionOrMethodDecl();
21145 
21146  if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
21147  return;
21148 
21149  // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
21150  // all TCBs the callee is a part of.
21151  llvm::StringSet<> CalleeTCBs;
21152  for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
21153  CalleeTCBs.insert(A->getTCBName());
21154  for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
21155  CalleeTCBs.insert(A->getTCBName());
21156 
21157  // Go through the TCBs the caller is a part of and emit warnings if Caller
21158  // is in a TCB that the Callee is not.
21159  for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
21160  StringRef CallerTCB = A->getTCBName();
21161  if (CalleeTCBs.count(CallerTCB) == 0) {
21162  this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
21163  << Callee << CallerTCB;
21164  }
21165  }
21166 }
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3278
NodeId Parent
Definition: ASTDiff.cpp:191
SyntaxTree::Impl & Tree
Definition: ASTDiff.cpp:192
int Depth
Definition: ASTDiff.cpp:190
ASTImporterLookupTable & LT
StringRef P
Provides definitions for the various language-specific address spaces.
static char ID
Definition: Arena.cpp:183
#define SM(sm)
Definition: Cuda.cpp:82
Defines the Diagnostic-related interfaces.
static constexpr Builtin::Info BuiltinInfo[]
Definition: Builtins.cpp:32
llvm::APSInt APSInt
static bool getTypeString(SmallStringEnc &Enc, const Decl *D, const CodeGen::CodeGenModule &CGM, TypeStringCache &TSC)
The XCore ABI includes a type information section that communicates symbol type information to the li...
Definition: XCore.cpp:632
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1109
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
unsigned Offset
Definition: Format.cpp:2974
const CFGBlock * Block
Definition: HTMLLogger.cpp:153
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
CompileCommand Cmd
LangStandard::Kind Std
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition: MachO.h:48
llvm::MachO::Record Record
Definition: MachO.h:31
Defines the clang::OpenCLOptions class.
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
static bool BuiltinReserveRWPipe(Sema &S, CallExpr *Call)
static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, const ValueDecl **VD, uint64_t *MagicValue, bool isConstantEvaluated)
Given a type tag expression find the type tag itself.
static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, bool InConstantContext, bool Approximate)
Pseudo-evaluate the given integer expression, estimating the range of values it might take.
static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, SourceLocation CC, QualType T)
static QualType getSizeOfArgType(const Expr *E)
If E is a sizeof expression, returns its argument type.
static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, SourceLocation CallSiteLoc)
static std::optional< unsigned > getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S)
static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, IdentifierInfo *FnName, SourceLocation FnLoc, SourceLocation RParenLoc)
Takes the expression passed to the size_t parameter of functions such as memcmp, strncat,...
static std::pair< QualType, StringRef > shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy, const Expr *E)
static ExprResult PointerAuthSignGenericData(Sema &S, CallExpr *Call)
static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext)
Diagnose an implicit cast from a floating point value to an integer value.
static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, const Expr *OrigFormatExpr, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type, bool inFunctionCall, Sema::VariadicCallType CallType, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, bool IgnoreStringsWithoutSpecifiers)
static ExprResult PointerAuthStrip(Sema &S, CallExpr *Call)
static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner)
Consider whether capturing the given variable can possibly lead to a retain cycle.
static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, bool *ICContext=nullptr, bool IsListInit=false)
static bool IsSameFloatAfterCast(const llvm::APFloat &value, const llvm::fltSemantics &Src, const llvm::fltSemantics &Tgt)
Checks whether the given value, which currently has the given source semantics, has the same value wh...
static StringLiteralCheckType checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type, Sema::VariadicCallType CallType, bool InFunctionCall, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset, bool IgnoreStringsWithoutSpecifiers=false)
static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth)
static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool)
static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, SourceLocation CContext, unsigned diag, bool pruneControlFlow=false)
Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg)
OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local void*, which is a requirem...
static bool isX86_32Builtin(unsigned BuiltinID)
static void AnalyzeComparison(Sema &S, BinaryOperator *E)
Implements -Wsign-compare.
static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, BinaryOperatorKind BinOpKind, bool AddendIsRight)
static QualType GetExprType(const Expr *E)
static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, SourceLocation CC)
static bool OpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall)
OpenCL C v2.0, s6.13.17.6 - Check the argument to the get_kernel_work_group_size and get_kernel_prefe...
static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, Expr *Constant, Expr *Other, const llvm::APSInt &Value, bool RhsConstant)
static AbsoluteValueKind getAbsoluteValueKind(QualType T)
bool CheckNoDoubleVectors(Sema *S, CallExpr *TheCall)
static bool isKnownToHaveUnsignedValue(Expr *E)
static const UnaryExprOrTypeTraitExpr * getAsSizeOfExpr(const Expr *E)
static ExprResult BuiltinDumpStruct(Sema &S, CallExpr *TheCall)
static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2)
Check if two standard-layout structs are layout-compatible.
bool CheckUnsignedIntRepresentation(Sema *S, CallExpr *TheCall)
bool CheckVectorElementCallArgs(Sema *S, CallExpr *TheCall)
static unsigned RFT(unsigned t, bool shift=false, bool ForceQuad=false)
static bool hasArmZAState(const FunctionDecl *FD)
static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntType)
Diagnose integer type and any valid implicit conversion to it.
static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op)
static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, Scope::ScopeFlags NeededScopeFlags, unsigned DiagID)
static llvm::APSInt getSYCLAllocaDefaultSize(const ASTContext &Ctx, const VarDecl *VD)
static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E)
Analyze the given compound assignment for the possible losing of floating-point precision.
static bool doesExprLikelyComputeSize(const Expr *SizeofExpr)
Detect if SizeofExpr is likely to calculate the sizeof an object.
static const Expr * getSizeOfExprArg(const Expr *E)
If E is a sizeof expression, returns its argument expression, otherwise returns NULL.
static bool isObjCSignedCharBool(Sema &S, QualType Ty)
static bool checkIntelFPGARegArgument(Sema &S, QualType ArgType, SourceLocation &Loc)
static bool OpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, CallExpr *Call)
static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall)
Check the number of arguments and set the result type to the argument type.
bool CheckFloatOrHalfRepresentations(Sema *S, CallExpr *TheCall)
static bool isValidBPFPreserveTypeInfoArg(Expr *Arg)
static bool CheckForReference(Sema &SemaRef, const Expr *E, const PartialDiagnostic &PD)
static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy, int ArgIndex)
static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID)
Check that the value argument for __builtin_is_aligned(value, alignment) and __builtin_aligned_{up,...
static std::optional< int > GetNSMutableDictionaryArgumentIndex(Sema &S, ObjCMessageExpr *Message)
static bool BuiltinRWPipe(Sema &S, CallExpr *Call)
static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC)
Check conversion of given expression to boolean.
static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind)
static bool checkArgCountAtLeast(Sema &S, CallExpr *Call, unsigned MinArgCount)
Checks that a call expression's argument count is at least the desired number.
static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call)
Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the last two arguments transpose...
static bool checkPointerAuthEnabled(Sema &S, Expr *E)
static std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range)
AbsoluteValueKind
@ AVK_Complex
@ AVK_Floating
@ AVK_Integer
static std::pair< CharUnits, CharUnits > getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, CharUnits BaseAlignment, CharUnits Offset, ASTContext &Ctx)
Compute the alignment and offset of the base class object given the derived-to-base cast expression a...
static void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, ObjCDictionaryLiteral *DictionaryLiteral)
Check an Objective-C dictionary literal being converted to the given target type.
static void checkArmStreamingBuiltin(Sema &S, CallExpr *TheCall, const FunctionDecl *FD, ArmStreamingType BuiltinType)
static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, ASTContext &Context)
static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall, const TargetInfo *AuxTI, unsigned BuiltinID)
BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
static bool isBlockPointer(Expr *Arg)
static bool isSetterLikeSelector(Selector sel)
Check for a keyword selector that starts with the word 'add' or 'set'.
static bool CheckWasmBuiltinArgIsTable(Sema &S, CallExpr *E, unsigned ArgIndex, QualType &ElTy)
Checks the argument at the given index is a WebAssembly table and if it is, sets ElTy to the element ...
static void adornObjCBoolConversionDiagWithTernaryFixit(Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder)
static bool OpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall)
OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different overload formats specified ...
static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, Expr *BlockArg, unsigned NumNonVarArgs)
OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 'local void*' parameter of passed blo...
static bool BuiltinCommitRWPipe(Sema &S, CallExpr *Call)
static bool IsSameCharType(QualType T1, QualType T2)
bool CheckAllArgsHaveFloatRepresentation(Sema *S, CallExpr *TheCall)
static bool CheckNonNullExpr(Sema &S, const Expr *Expr)
Checks if a the given expression evaluates to null.
static const CXXRecordDecl * getContainedDynamicClass(QualType T, bool &IsContained)
Determine whether the given type is or contains a dynamic class type (e.g., whether it has a vtable).
static Expr * findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner)
Check whether the given argument is a block which captures a variable.
static bool isArgumentExpandedFromMacro(SourceManager &SM, SourceLocation CallLoc, SourceLocation ArgLoc)
Check if the ArgLoc originated from a macro passed to the call at CallLoc.
static ArmStreamingType getArmStreamingFnType(const FunctionDecl *FD)
static const Expr * maybeConstEvalStringLiteral(ASTContext &Context, const Expr *E)
static bool IsStdFunction(const FunctionDecl *FDecl, const char(&Str)[StrLen])
static void AnalyzeAssignment(Sema &S, BinaryOperator *E)
Analyze the given simple or compound assignment for warning-worthy operations.
static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall)
Check that the argument to __builtin_function_start is a function.
static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall)
static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, SourceLocation StmtLoc, const NullStmt *Body)
static std::optional< std::pair< CharUnits, CharUnits > > getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, bool IsSub, ASTContext &Ctx)
Compute the alignment and offset of a binary additive operator.
static void diagnoseArrayStarInParamType(Sema &S, QualType PType, SourceLocation Loc)
static ArmSMEState getSMEState(unsigned BuiltinID)
static unsigned changeAbsFunction(unsigned AbsKind, AbsoluteValueKind ValueKind)
static const Expr * ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx)
static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, SourceLocation CC, bool &ICContext)
static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2)
Check if two types are layout-compatible in C++11 sense.
static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
static bool isValidBPFPreserveFieldInfoArg(Expr *Arg)
static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, Expr *RHS, bool isProperty)
static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall)
static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx)
Returns true if pipe element type is different from the pointer.
static ExprResult PointerAuthBlendDiscriminator(Sema &S, CallExpr *Call)
static const IntegerLiteral * getIntegerLiteral(Expr *E)
static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, SourceLocation InitLoc)
Analyzes an attempt to assign the given value to a bitfield.
static int classifyConstantValue(Expr *Constant)
static llvm::SmallPtrSet< MemberKind *, 1 > CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty)
static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc)
static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, unsigned AbsKind, QualType ArgType)
static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call)
Returns true if pipe element type is different from the pointer.
static bool checkPointerAuthKey(Sema &S, Expr *&Arg)
static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, Qualifiers::ObjCLifetime LT, Expr *RHS, bool isProperty)
static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID)
static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl)
static void diagnoseRetainCycle(Sema &S, Expr *capturer, RetainCycleOwner &owner)
static std::optional< std::pair< CharUnits, CharUnits > > getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx)
This helper function takes an lvalue expression and returns the alignment of a VarDecl and a constant...
static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, bool IsPolyUnsigned, bool IsInt64Long)
getNeonEltType - Return the QualType corresponding to the elements of the vector type specified by th...
static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
static bool CheckBuiltinTargetInSupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall, ArrayRef< llvm::Triple::ArchType > SupportedArchs)
static void CheckNonNullArguments(Sema &S, const NamedDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< const Expr * > Args, SourceLocation CallSiteLoc)
static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction)
static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner)
static bool hasArmZT0State(const FunctionDecl *FD)
static analyze_format_string::ArgType::MatchKind handleFormatSignedness(analyze_format_string::ArgType::MatchKind Match, DiagnosticsEngine &Diags, SourceLocation Loc)
static bool referToTheSameDecl(const Expr *E1, const Expr *E2)
Check if two expressions refer to the same declaration.
static bool OpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall)
#define BUILTIN_ROW(x)
static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall)
Checks that __builtin_{clzg,ctzg} was called with a first argument, which is an unsigned integer,...
static bool requiresParensToAddCast(const Expr *E)
static ExprResult PointerAuthAuthAndResign(Sema &S, CallExpr *Call)
static void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType, Expr *Element, unsigned ElementKind)
Check a single element within a collection literal against the target element type.
static bool BuiltinPipePackets(Sema &S, CallExpr *Call)
static bool CheckWasmBuiltinArgIsInteger(Sema &S, CallExpr *E, unsigned ArgIndex)
Checks the argument at the given index is an integer.
static bool checkArgCountRange(Sema &S, CallExpr *Call, unsigned MinArgCount, unsigned MaxArgCount)
Checks that a call expression's argument count is in the desired range.
static bool convertArgumentToType(Sema &S, Expr *&Value, QualType Ty)
static bool ProcessFormatStringLiteral(const Expr *FormatExpr, StringRef &FormatStrRef, size_t &StrLen, ASTContext &Context)
static bool checkArgCount(Sema &S, CallExpr *Call, unsigned DesiredArgCount)
Checks that a call expression's argument count is the desired number.
static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall)
Checks that __builtin_popcountg was called with a single argument, which is an unsigned integer.
void SetElementTypeAsReturnType(Sema *S, CallExpr *TheCall, QualType ReturnType)
static void DiagnoseIntInBoolContext(Sema &S, Expr *E)
static std::optional< int > GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message)
static bool CheckBuiltinTargetNotInUnsupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall, ArrayRef< llvm::Triple::ObjectFormatType > UnsupportedObjectFormatTypes)
static bool BuiltinAddressof(Sema &S, CallExpr *TheCall)
Check that the argument to __builtin_addressof is a glvalue, and set the result type to the correspon...
static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S)
static OpenCLAccessAttr * getOpenCLArgAccess(const Decl *D)
Returns OpenCL access qual.
static ExprResult PointerAuthSignOrAuth(Sema &S, CallExpr *Call, PointerAuthOpKind OpKind)
static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn)
Check that the user is calling the appropriate va_start builtin for the target and calling convention...
static bool IsEnumConstOrFromMacro(Sema &S, Expr *E)
static const Expr * getStrlenExprArg(const Expr *E)
ArmStreamingType
@ ArmStreamingOrSVE2p1
@ ArmStreaming
@ ArmStreamingCompatible
@ ArmNonStreaming
static bool CheckInvalidVLENandLMUL(const TargetInfo &TI, CallExpr *TheCall, Sema &S, QualType Type, int EGW)
static bool GetMatchingCType(const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, const ASTContext &Ctx, const llvm::DenseMap< Sema::TypeTagMagicValue, Sema::TypeTagData > *MagicValues, bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, bool isConstantEvaluated)
Retrieve the C type corresponding to type tag TypeExpr.
static void checkObjCArrayLiteral(Sema &S, QualType TargetType, ObjCArrayLiteral *ArrayLiteral)
Check an Objective-C array literal being converted to the given target type.
static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2)
Check if two standard-layout unions are layout-compatible.
static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, unsigned &Mask)
DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str, advancing the pointer ov...
static QualType getAbsoluteValueArgumentType(ASTContext &Context, unsigned AbsType)
static void DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, const NamedDecl *FDecl, Expr **Args, unsigned NumArgs)
Diagnose use of s directive in an NSString which is being passed as formatting string to formatting m...
static bool isNonNullType(QualType type)
Determine whether the given type has a non-null nullability annotation.
static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A, Sema::FormatArgumentPassingKind B)
static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall)
Check that the first argument to __builtin_annotation is an integer and the second argument is a non-...
static std::optional< std::pair< CharUnits, CharUnits > > getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx)
This helper function takes a pointer expression and returns the alignment of a VarDecl and a constant...
static bool IsShiftedByte(llvm::APSInt Value)
static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, unsigned AbsFunctionKind)
static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex)
checkBuiltinArgument - Given a call to a builtin function, perform normal type-checking on the given ...
static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E)
Analyze the operands of the given comparison.
@ TileRegHigh
@ TileRegLow
static std::optional< int > GetNSMutableArrayArgumentIndex(Sema &S, ObjCMessageExpr *Message)
static bool isPPC_64Builtin(unsigned BuiltinID)
static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call)
static bool isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE)
Return true if ICE is an implicit argument promotion of an arithmetic type.
static bool isValidBPFPreserveEnumValueArg(Expr *Arg)
static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, bool IsListInit=false)
AnalyzeImplicitConversions - Find and report any interesting implicit conversions in the given expres...
static bool HasEnumType(Expr *E)
static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, unsigned Start, unsigned End)
static bool checkFPMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy, int ArgIndex)
ArmSMEState
@ ArmInOutZA
@ ArmOutZA
@ ArmInZT0
@ ArmNoState
@ ArmZT0Mask
@ ArmZAMask
@ ArmOutZT0
@ ArmInOutZT0
@ ArmInZA
static bool checkArgCountAtMost(Sema &S, CallExpr *Call, unsigned MaxArgCount)
Checks that a call expression's argument count is at most the desired number.
static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall)
static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, ParmVarDecl **LastParam=nullptr)
bool CheckArgsTypesAreCorrect(Sema *S, CallExpr *TheCall, QualType ExpectedType, llvm::function_ref< bool(clang::QualType PassedType)> Check)
This file declares semantic analysis for SYCL constructs.
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
Provides definitions for the atomic synchronization scopes.
Enumerates target-specific builtins in their own namespaces within namespace clang.
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we're targeting.
Defines the clang::TypeLoc interface and its subclasses.
Defines enumerations for the type traits support.
C Language Family Type Representation.
const NestedNameSpecifier * Specifier
SourceLocation End
std::string Label
__DEVICE__ int min(int __a, int __b)
__DEVICE__ int max(int __a, int __b)
__device__ int
__device__ __2f16 float __ockl_bool s
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
bool isVector() const
Definition: APValue.h:407
unsigned getStructNumFields() const
Definition: APValue.h:542
APFloat & getFloat()
Definition: APValue.h:437
bool isComplexInt() const
Definition: APValue.h:404
ValueKind getKind() const
Definition: APValue.h:395
bool isFloat() const
Definition: APValue.h:402
APSInt & getComplexIntReal()
Definition: APValue.h:453
bool isComplexFloat() const
Definition: APValue.h:405
unsigned getVectorLength() const
Definition: APValue.h:505
APSInt & getComplexIntImag()
Definition: APValue.h:461
bool isLValue() const
Definition: APValue.h:406
APValue & getStructField(unsigned i)
Definition: APValue.h:551
APFloat & getComplexFloatImag()
Definition: APValue.h:477
bool isInt() const
Definition: APValue.h:401
APSInt & getInt()
Definition: APValue.h:423
APFloat & getComplexFloatReal()
Definition: APValue.h:469
APValue & getVectorElt(unsigned I)
Definition: APValue.h:497
bool isAddrLabelDiff() const
Definition: APValue.h:412
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:697
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
CanQualType LongTy
Definition: ASTContext.h:1100
unsigned getIntWidth(QualType T) const
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType) const
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
QualType getRecordType(const RecordDecl *Decl) const
CanQualType FloatTy
Definition: ASTContext.h:1103
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2568
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2584
CanQualType DoubleTy
Definition: ASTContext.h:1103
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
CanQualType LongDoubleTy
Definition: ASTContext.h:1103
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
Definition: ASTContext.h:1118
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1119
IdentifierTable & Idents
Definition: ASTContext.h:644
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:646
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2761
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const
Compare the rank of two floating point types as above, but compare equal if both types have the same ...
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:775
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
CanQualType BoolTy
Definition: ASTContext.h:1092
CanQualType Float128Ty
Definition: ASTContext.h:1103
CanQualType UnsignedLongTy
Definition: ASTContext.h:1101
llvm::APFixedPoint getFixedPointMin(QualType Ty) const
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType CharTy
Definition: ASTContext.h:1093
CanQualType IntTy
Definition: ASTContext.h:1100
QualType getWebAssemblyExternrefType() const
Return a WebAssembly externref type.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2160
CanQualType SignedCharTy
Definition: ASTContext.h:1100
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
CanQualType OCLClkEventTy
Definition: ASTContext.h:1132
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2611
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2334
CanQualType BuiltinFnTy
Definition: ASTContext.h:1120
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
Definition: ASTContext.h:1091
CanQualType UnsignedCharTy
Definition: ASTContext.h:1101
CanQualType UnsignedIntTy
Definition: ASTContext.h:1101
QualType getExceptionObjectType(QualType T) const
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1102
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
CanQualType OCLReserveIDTy
Definition: ASTContext.h:1133
CanQualType UnsignedShortTy
Definition: ASTContext.h:1101
bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1572
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:757
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
CanQualType ShortTy
Definition: ASTContext.h:1100
StringLiteral * getPredefinedStringLiteralFromCache(StringRef Key) const
Return a string representing the human readable name for the specified function declaration or file n...
llvm::APFixedPoint getFixedPointMax(QualType Ty) const
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
bool areCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an SVE builtin and a VectorType that is a fixed-length representat...
CanQualType OCLQueueTy
Definition: ASTContext.h:1133
CanQualType BFloat16Ty
Definition: ASTContext.h:1116
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
CanQualType getNSIntegerType() const
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
const TargetInfo * getAuxTargetInfo() const
Definition: ASTContext.h:758
CanQualType LongLongTy
Definition: ASTContext.h:1100
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
QualType getTypedefType(const TypedefNameDecl *Decl, QualType Underlying=QualType()) const
Return the unique reference to the type for the specified typedef-name decl.
QualType DecodeTypeStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequireICE, bool AllowTypeModifiers) const
@ GE_None
No error.
Definition: ASTContext.h:2236
CanQualType HalfTy
Definition: ASTContext.h:1115
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns) const
Return the unique reference to the matrix type of the specified element type and size.
CanQualType getNSUIntegerType() const
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2338
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:200
CharUnits getNonVirtualAlignment() const
getNonVirtualAlignment - Get the non-virtual alignment (in chars) of an object, which is the alignmen...
Definition: RecordLayout.h:218
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:249
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition: Expr.h:4193
Expr * getCond() const
getCond - Return the expression representing the condition for the ?: operator.
Definition: Expr.h:4371
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition: Expr.h:4377
SourceLocation getQuestionLoc() const
Definition: Expr.h:4220
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition: Expr.h:4383
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2716
SourceLocation getRBracketLoc() const
Definition: Expr.h:2764
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition: Expr.h:2745
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3318
ArraySizeModifier getSizeModifier() const
Definition: Type.h:3332
QualType getElementType() const
Definition: Type.h:3330
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition: Expr.h:6478
std::unique_ptr< AtomicScopeModel > getScopeModel() const
Get atomic scope model.
Definition: Expr.h:6619
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:6585
Attr - This represents one attribute.
Definition: Attr.h:46
const char * getSpelling() const
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3892
static bool isLogicalOp(Opcode Opc)
Definition: Expr.h:4024
SourceLocation getOperatorLoc() const
Definition: Expr.h:3933
SourceLocation getExprLoc() const
Definition: Expr.h:3932
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition: Expr.cpp:2189
bool isEqualityOp() const
Definition: Expr.h:3989
static bool isAdditiveOp(Opcode Opc)
Definition: Expr.h:3977
Opcode getOpcode() const
Definition: Expr.h:3936
Expr * getRHS() const
Definition: Expr.h:3943
static bool isEqualityOp(Opcode Opc)
Definition: Expr.h:3988
Expr * getLHS() const
Definition: Expr.h:3941
A fixed int type of a specified bitwidth.
Definition: Type.h:7042
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4496
Stmt * getBody() const override
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition: Decl.h:4575
bool capturesVariable(const VarDecl *var) const
Definition: Decl.cpp:5258
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:4602
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6214
const BlockDecl * getBlockDecl() const
Definition: Expr.h:6226
Pointer to a block type.
Definition: Type.h:3149
QualType getPointeeType() const
Definition: Type.h:3161
This class is used for builtin types like 'int'.
Definition: Type.h:2777
bool isInteger() const
Definition: Type.h:2836
bool isFloatingPoint() const
Definition: Type.h:2848
bool isSignedInteger() const
Definition: Type.h:2840
bool isUnsignedInteger() const
Definition: Type.h:2844
Kind getKind() const
Definition: Type.h:2823
bool isAuxBuiltinID(unsigned ID) const
Return true if builtin ID belongs to AuxTarget.
Definition: Builtins.h:262
llvm::StringRef getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.h:103
unsigned getAuxBuiltinID(unsigned ID) const
Return real builtin ID (i.e.
Definition: Builtins.h:268
bool isTSBuiltin(unsigned ID) const
Return true if this function is a target-specific builtin.
Definition: Builtins.h:111
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name.
Definition: Builtins.h:222
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr....
Definition: Expr.h:3823
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1540
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
Definition: ExprCXX.h:1622
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition: ExprCXX.h:1680
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2796
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2057
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:81
SourceLocation getExprLoc() const LLVM_READONLY
Definition: ExprCXX.h:151
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition: ExprCXX.h:111
Represents a list-initialization with parenthesis.
Definition: ExprCXX.h:4920
ArrayRef< Expr * > getInitExprs()
Definition: ExprCXX.h:4960
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition: DeclCXX.h:1225
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:612
base_class_iterator bases_begin()
Definition: DeclCXX.h:625
bool isDynamicClass() const
Definition: DeclCXX.h:584
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:564
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:73
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2872
Expr ** getArgs()
Retrieve the call arguments.
Definition: Expr.h:3053
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:3076
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1693
arg_iterator arg_begin()
Definition: Expr.h:3116
arg_iterator arg_end()
Definition: Expr.h:3119
bool isCallToStdMove() const
Definition: Expr.cpp:3562
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:1702
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:3050
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3063
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition: Expr.h:3148
arg_range arguments()
Definition: Expr.h:3111
SourceLocation getRParenLoc() const
Definition: Expr.h:3182
Expr * getCallee()
Definition: Expr.h:3022
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:3042
Decl * getCalleeDecl()
Definition: Expr.h:3036
bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const
Returns true if this is a call to a builtin which does not evaluate side-effects within its arguments...
Definition: Expr.cpp:1639
void setCallee(Expr *F)
Definition: Expr.h:3024
QualType withConst() const
Retrieves a version of this type with const applied.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:83
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3535
path_iterator path_begin()
Definition: Expr.h:3605
CastKind getCastKind() const
Definition: Expr.h:3579
Expr * getSubExpr()
Definition: Expr.h:3585
path_iterator path_end()
Definition: Expr.h:3606
Represents a character-granular source range.
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
SourceLocation getBegin() const
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
bool isOne() const
isOne - Test whether the quantity equals one.
Definition: CharUnits.h:125
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
Complex values, per C99 6.2.5p11.
Definition: Type.h:2886
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:4140
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4231
Expr * getLHS() const
Definition: Expr.h:4265
Expr * getRHS() const
Definition: Expr.h:4266
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3356
QualType desugar() const
Definition: Type.h:3457
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3412
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:3967
static constexpr unsigned getMaxElementsPerDimension()
Returns the maximum number of elements per dimension.
Definition: Type.h:4001
static constexpr bool isDimensionValid(size_t NumElements)
Returns true if NumElements is a valid matrix dimension.
Definition: Type.h:3996
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
Definition: Expr.h:4551
Represents an expression that might suspend coroutine execution; either a co_await or co_yield expres...
Definition: ExprCXX.h:5037
child_range children()
Definition: ExprCXX.h:5136
Expr * getOperand() const
Definition: ExprCXX.h:5106
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2344
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1438
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2068
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2324
bool isFunctionOrMethod() const
Definition: DeclBase.h:2120
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
ValueDecl * getDecl()
Definition: Expr.h:1328
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:551
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition: Expr.cpp:488
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition: Expr.h:1347
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition: Expr.h:1452
SourceLocation getLocation() const
Definition: Expr.h:1336
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:85
bool isInStdNamespace() const
Definition: DeclBase.cpp:403
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition: DeclBase.cpp:515
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
Definition: DeclBase.cpp:1116
bool isInvalidDecl() const
Definition: DeclBase.h:596
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:970
SourceLocation getLocation() const
Definition: DeclBase.h:447
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:567
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:439
bool hasAttr() const
Definition: DeclBase.h:585
T * getAttr() const
Definition: DeclBase.h:581
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:435
The name of a declaration.
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1989
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:823
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:800
RAII class that determines when any errors have occurred between the time the instance was created an...
Definition: Diagnostic.h:1083
bool hasErrorOccurred() const
Determine whether any errors have occurred since this object instance was created.
Definition: Diagnostic.h:1094
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:193
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:922
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3299
Represents an enum.
Definition: Decl.h:3869
unsigned getNumNegativeBits() const
Returns the width in bits required to store all the negative enumerators of this enum.
Definition: Decl.h:4066
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4088
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4029
TypeSourceInfo * getIntegerTypeSourceInfo() const
Return the type source info for the underlying integer type, if no type source info exists,...
Definition: Decl.h:4045
unsigned getNumPositiveBits() const
Returns the width in bits required to store all the non-negative enumerators of this enum.
Definition: Decl.h:4055
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5375
EvaluatedExprVisitor - This class visits 'Expr *'s.
This represents one expression.
Definition: Expr.h:110
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition: Expr.h:671
@ SE_NoSideEffects
Strictly evaluate the expression.
Definition: Expr.h:668
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3116
void setType(QualType t)
Definition: Expr.h:143
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
bool tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const
If the current Expr is a pointer, this will try to statically determine the strlen of the string poin...
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3111
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3099
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:245
bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFloat - Return true if this is a constant which we can fold and convert to a floating point...
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3107
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFixedPoint - Return true if this is a constant which we can fold and convert to a fixed poi...
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:4136
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:821
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:825
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:444
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Expr * IgnoreImplicitAsWritten() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3103
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition: Expr.cpp:3608
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition: Expr.h:221
bool isIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3091
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition: Expr.h:792
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition: Expr.h:801
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition: Expr.h:804
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition: Expr.h:794
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition: Expr.cpp:3975
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition: Expr.cpp:266
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition: Expr.h:454
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition: Expr.h:457
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool isFlexibleArrayMemberLike(ASTContext &Context, LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel, bool IgnoreTemplateOrMacroSubstitution=false) const
Check whether this array fits the idiom of a flexible array member, depending on the value of -fstric...
Definition: Expr.cpp:206
QualType getType() const
Definition: Expr.h:142
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:516
bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
const ValueDecl * getAsBuiltinConstantDeclRef(const ASTContext &Context) const
If this expression is an unambiguous reference to a single declaration, in the style of __builtin_fun...
Definition: Expr.cpp:226
bool isKnownToHaveBooleanValue(bool Semantic=true) const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition: Expr.cpp:136
void EvaluateForOverflow(const ASTContext &Ctx) const
ExtVectorType - Extended vector type.
Definition: Type.h:3861
Represents a member of a struct/union/class.
Definition: Decl.h:3059
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3150
unsigned getBitWidthValue(const ASTContext &Ctx) const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4598
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3272
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition: Decl.h:3163
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:72
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:135
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:124
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:98
llvm::APFloat getValue() const
Definition: Expr.h:1647
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition: Stmt.h:2781
Represents a function declaration or definition.
Definition: Decl.h:1972
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition: Decl.cpp:4405
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3717
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3636
param_iterator param_end()
Definition: Decl.h:2698
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3735
QualType getReturnType() const
Definition: Decl.h:2756
param_iterator param_begin()
Definition: Decl.h:2697
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3093
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4182
bool isStatic() const
Definition: Decl.h:2840
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3997
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2685
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3983
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3696
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2708
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4456
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4696
unsigned getNumParams() const
Definition: Type.h:4689
QualType getParamType(unsigned i) const
Definition: Type.h:4691
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition: Type.h:4894
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:4812
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4700
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition: Type.h:4807
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4056
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition: Type.h:4343
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition: Type.h:4339
QualType getReturnType() const
Definition: Type.h:4373
@ SME_PStateSMEnabledMask
Definition: Type.h:4317
@ SME_PStateSMCompatibleMask
Definition: Type.h:4318
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3707
Describes an C or C++ initializer list.
Definition: Expr.h:4888
ArrayRef< Expr * > inits()
Definition: Expr.h:4928
Describes an entity that is being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:1032
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:475
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition: Lexer.cpp:1024
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition: Lexer.cpp:1060
static unsigned MeasureTokenLength(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
MeasureTokenLength - Relex the token at the specified location and return its length in bytes in the ...
Definition: Lexer.cpp:499
static StringRef getImmediateMacroNameForDiagnostics(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition: Lexer.cpp:1107
static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset, const SourceManager &SM, const LangOptions &LangOpts)
Computes the source location just past the end of the token at this source location.
Definition: Lexer.cpp:850
Represents the results of name lookup.
Definition: Lookup.h:46
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:566
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:331
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:632
iterator end() const
Definition: Lookup.h:359
iterator begin() const
Definition: Lookup.h:358
static bool isValidElementType(QualType T)
Valid elements types are the following:
Definition: Type.h:3952
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3224
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3307
Expr * getBase() const
Definition: Expr.h:3301
bool isArrow() const
Definition: Expr.h:3408
@ ClassId_NSMutableArray
Definition: NSAPI.h:33
@ ClassId_NSMutableOrderedSet
Definition: NSAPI.h:38
@ ClassId_NSMutableSet
Definition: NSAPI.h:37
@ ClassId_NSMutableDictionary
Definition: NSAPI.h:35
NSSetMethodKind
Enumerates the NSMutableSet/NSOrderedSet methods used to apply some checks.
Definition: NSAPI.h:121
@ NSOrderedSet_setObjectAtIndex
Definition: NSAPI.h:124
@ NSMutableSet_addObject
Definition: NSAPI.h:122
@ NSOrderedSet_replaceObjectAtIndexWithObject
Definition: NSAPI.h:126
@ NSOrderedSet_setObjectAtIndexedSubscript
Definition: NSAPI.h:125
@ NSOrderedSet_insertObjectAtIndex
Definition: NSAPI.h:123
NSDictionaryMethodKind
Enumerates the NSDictionary/NSMutableDictionary methods used to generate literals and to apply some c...
Definition: NSAPI.h:96
@ NSMutableDict_setValueForKey
Definition: NSAPI.h:109
@ NSMutableDict_setObjectForKey
Definition: NSAPI.h:107
@ NSMutableDict_setObjectForKeyedSubscript
Definition: NSAPI.h:108
NSArrayMethodKind
Enumerates the NSArray/NSMutableArray methods used to generate literals and to apply some checks.
Definition: NSAPI.h:72
@ NSMutableArr_setObjectAtIndexedSubscript
Definition: NSAPI.h:84
@ NSMutableArr_insertObjectAtIndex
Definition: NSAPI.h:83
@ NSMutableArr_addObject
Definition: NSAPI.h:82
@ NSMutableArr_replaceObjectAtIndex
Definition: NSAPI.h:81
This represents a decl that may have a name.
Definition: Decl.h:249
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
ObjCStringFormatFamily getObjCFStringFormattingFamily() const
Definition: Decl.cpp:1156
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1200
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1931
Represent a C++ namespace.
Definition: Decl.h:548
Flags to identify the types for overloaded Neon builtins.
bool isUnsigned() const
EltType getEltType() const
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition: Stmt.h:1569
bool hasLeadingEmptyMacro() const
Definition: Stmt.h:1583
SourceLocation getSemiLoc() const
Definition: Stmt.h:1580
OpenMP 5.0 [2.1.5, Array Sections].
Definition: ExprOpenMP.h:56
Expr * getBase()
An array section can be written only as Base[LowerBound:Length].
Definition: ExprOpenMP.h:85
Expr * getLowerBound()
Get lower bound of array section.
Definition: ExprOpenMP.h:94
ObjCArrayLiteral - used for objective-c array containers; as in: @["Hello", NSApp,...
Definition: ExprObjC.h:191
unsigned getNumElements() const
getNumElements - Return number of elements of objective-c array literal.
Definition: ExprObjC.h:228
Expr * getElement(unsigned Index)
getElement - Return the Element at the specified index.
Definition: ExprObjC.h:231
ObjCDictionaryLiteral - AST node to represent objective-c dictionary literals; as in:"name" : NSUserN...
Definition: ExprObjC.h:309
unsigned getNumElements() const
getNumElements - Return number of elements of objective-c dictionary literal.
Definition: ExprObjC.h:360
ObjCDictionaryElement getKeyValueElement(unsigned Index) const
Definition: ExprObjC.h:362
Represents an ObjC class declaration.
Definition: DeclObjC.h:1152
ObjCInterfaceDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C class.
Definition: DeclObjC.h:1911
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1948
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:549
const Expr * getBase() const
Definition: ExprObjC.h:583
bool isFreeIvar() const
Definition: ExprObjC.h:588
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:945
SourceLocation getSuperLoc() const
Retrieve the location of the 'super' keyword for a class or instance message to 'super',...
Definition: ExprObjC.h:1301
Selector getSelector() const
Definition: ExprObjC.cpp:293
Expr * getInstanceReceiver()
Returns the object expression (receiver) for an instance message, or null for a message that is not a...
Definition: ExprObjC.h:1260
@ SuperInstance
The receiver is the instance of the superclass object.
Definition: ExprObjC.h:959
@ Instance
The receiver is an object instance.
Definition: ExprObjC.h:953
bool isInstanceMessage() const
Determine whether this is an instance message to either a computed object or to super.
Definition: ExprObjC.h:1248
const ObjCMethodDecl * getMethodDecl() const
Definition: ExprObjC.h:1356
ReceiverKind getReceiverKind() const
Determine the kind of receiver that this message is being sent to.
Definition: ExprObjC.h:1234
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: ExprObjC.h:1395
unsigned getNumArgs() const
Return the number of actual arguments in this message, not counting the receiver.
Definition: ExprObjC.h:1382
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
bool isVariadic() const
Definition: DeclObjC.h:431
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:418
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: DeclObjC.h:284
ArrayRef< ParmVarDecl * > parameters() const
Definition: DeclObjC.h:373
Represents a pointer to an Objective C object.
Definition: Type.h:6808
ArrayRef< QualType > getTypeArgs() const
Retrieve the type arguments for this type.
Definition: Type.h:6912
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:729
QualType getType() const
Definition: DeclObjC.h:802
ObjCPropertyAttribute::Kind getPropertyAttributesAsWritten() const
Definition: DeclObjC.h:825
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition: DeclObjC.h:813
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition: ExprObjC.h:617
ObjCPropertyDecl * getExplicitProperty() const
Definition: ExprObjC.h:706
const Expr * getBase() const
Definition: ExprObjC.h:755
bool isImplicitProperty() const
Definition: ExprObjC.h:703
SourceLocation getLocation() const
Definition: ExprObjC.h:762
bool isSuperReceiver() const
Definition: ExprObjC.h:775
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition: ExprObjC.h:51
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1168
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition: Expr.h:1218
bool isSupported(llvm::StringRef Ext, const LangOptions &LO) const
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:254
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:2182
Represents a parameter to a function.
Definition: Decl.h:1762
PipeType - OpenCL20.
Definition: Type.h:7008
QualType getElementType() const
Definition: Type.h:7019
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2939
QualType getPointeeType() const
Definition: Type.h:2949
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6346
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition: Expr.cpp:4932
A (possibly-)qualified type.
Definition: Type.h:738
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7243
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:7237
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2716
PrimitiveDefaultInitializeKind
Definition: Type.h:1245
QualType withoutLocalFastQualifiers() const
Definition: Type.h:1007
QualType withConst() const
Definition: Type.h:952
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:949
bool isAtLeastAsQualifiedAs(QualType Other) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition: Type.h:7341
bool isTrivialType(const ASTContext &Context) const
Return true if this is a trivial type per (C++0x [basic.types]p9)
Definition: Type.cpp:2618
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:805
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7159
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7285
bool isConstant(const ASTContext &Ctx) const
Definition: Type.h:898
QualType withVolatile() const
Definition: Type.h:960
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7199
bool isCXX98PODType(const ASTContext &Context) const
Return true if this is a POD type according to the rules of the C++98 standard, regardless of the cur...
Definition: Type.cpp:2569
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1230
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
QualType getCanonicalType() const
Definition: Type.h:7211
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7253
void removeLocalVolatile()
Definition: Type.h:7275
void removeLocalConst()
Definition: Type.h:7267
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7232
const Type * getTypePtrOrNull() const
Definition: Type.h:7163
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1125
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1234
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:176
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:169
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:165
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:179
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:182
bool hasUnaligned() const
Definition: Type.h:319
bool empty() const
Definition: Type.h:441
Represents a struct/union/class.
Definition: Decl.h:4170
field_iterator field_end() const
Definition: Decl.h:4379
field_range fields() const
Definition: Decl.h:4376
field_iterator field_begin() const
Definition: Decl.cpp:5074
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5349
RecordDecl * getDecl() const
Definition: Type.h:5359
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
ScopeFlags
ScopeFlags - These are bitfields that are or'd together when creating a scope, which defines the sort...
Definition: Scope.h:45
@ SEHFilterScope
We are currently in the filter expression of an SEH except block.
Definition: Scope.h:131
@ SEHExceptScope
This scope corresponds to an SEH except.
Definition: Scope.h:128
Smart pointer class that efficiently represents Objective-C method names.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
bool isUnarySelector() const
unsigned getNumArgs() const
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:57
@ KernelCallVariadicFunction
Definition: SemaSYCL.h:310
static bool isSyclType(QualType Ty, SYCLTypeAttr::SYCLType TypeName)
Check whether Ty corresponds to a SYCL type of name TypeName.
Definition: SemaSYCL.cpp:73
SemaDiagnosticBuilder DiagIfDeviceCode(SourceLocation Loc, unsigned DiagID, DeviceDiagnosticReason Reason=DeviceDiagnosticReason::Sycl|DeviceDiagnosticReason::Esimd)
Creates a SemaDiagnosticBuilder that emits the diagnostic if the current context is "used as device c...
Definition: SemaSYCL.cpp:4613
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:458
bool IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base, const TypeSourceInfo *Derived)
void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opcode)
Check for comparisons of floating-point values using == and !=.
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:522
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7545
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:7553
@ LookupAnyName
Look up any declaration with any name.
Definition: Sema.h:7590
VariadicCallType
Definition: Sema.h:2014
@ VariadicDoesNotApply
Definition: Sema.h:2019
void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull)
Register a magic integral constant to be used as a type tag.
void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range)
Diagnose pointers that are always non-null.
bool FormatStringHasSArg(const StringLiteral *FExpr)
ObjCInterfaceDecl * NSDictionaryDecl
The declaration of the Objective-C NSDictionary class.
Definition: Sema.h:12416
static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, bool IsVariadic, FormatStringInfo *FSI)
Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo parameter with the Format...
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition: Sema.h:12380
void RefersToMemberWithReducedAlignment(Expr *E, llvm::function_ref< void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action)
This function calls Action when it determines that E designates a misaligned member due to the packed...
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
Definition: SemaExpr.cpp:12098
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition: Sema.cpp:1541
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
Definition: SemaExpr.cpp:864
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
Definition: SemaExpr.cpp:14556
ASTContext & Context
Definition: Sema.h:859
static FormatStringType GetFormatStringType(const FormatAttr *Format)
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:830
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:16098
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:699
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:672
bool BuiltinVectorToScalarMath(CallExpr *TheCall)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:776
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1546
bool CheckHLSLBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
Warn if a value is moved to itself.
AtomicArgumentOrder
Definition: Sema.h:1963
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:63
bool IsLayoutCompatible(QualType T1, QualType T2) const
bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type of the given expression is complete.
Definition: SemaType.cpp:9338
void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange)
CheckCastAlign - Implements -Wcast-align, which warns when a pointer cast increases the alignment req...
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:6717
bool hasCStrMethod(const Expr *E)
Check to see if a given expression could have '.c_str()' called on it.
const LangOptions & LangOpts
Definition: Sema.h:857
const LangOptions & getLangOpts() const
Definition: Sema.h:521
static const uint64_t MaximumAlignment
Definition: Sema.h:799
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
ObjCLiteralKind
Definition: Sema.h:5889
@ LK_String
Definition: Sema.h:5894
@ LK_None
Definition: Sema.h:5896
bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key)
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS)
checkUnsafeAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained type.
static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx)
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition: SemaExpr.cpp:1012
ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op)
Definition: SemaCast.cpp:3359
void DiagnoseMisalignedMembers()
Diagnoses the current set of gathered accesses.
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
void pushCodeSynthesisContext(CodeSynthesisContext Ctx)
std::pair< const IdentifierInfo *, uint64_t > TypeTagMagicValue
A pair of ArgumentKind identifier and magic value.
Definition: Sema.h:1941
bool isValidPointerAttrType(QualType T, bool RefOkay=false)
Determine if type T is a valid subject for a nonnull and similar attributes.
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
Definition: SemaExpr.cpp:10085
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition: Sema.cpp:2179
void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body, unsigned DiagID)
Emit DiagID if statement located on StmtLoc has a suspicious null statement as a Body,...
void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody)
Warn if a for/while loop statement S, which is followed by PossibleBody, has a suspicious null statem...
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:719
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const
bool BuiltinVectorMath(CallExpr *TheCall, QualType &Res)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:997
@ VAK_Invalid
Definition: Sema.h:6222
@ VAK_Valid
Definition: Sema.h:6218
@ VAK_ValidInCXX11
Definition: Sema.h:6219
@ VAK_MSVCUndefined
Definition: Sema.h:6221
@ VAK_Undefined
Definition: Sema.h:6220
SemaSYCL & SYCL()
Definition: Sema.h:1019
FormatArgumentPassingKind
Definition: Sema.h:1873
@ FAPK_Fixed
Definition: Sema.h:1874
@ FAPK_Variadic
Definition: Sema.h:1875
@ FAPK_VAList
Definition: Sema.h:1876
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:6262
SourceManager & getSourceManager() const
Definition: Sema.h:526
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:21293
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:10677
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
ObjCInterfaceDecl * NSArrayDecl
The declaration of the Objective-C NSArray class.
Definition: Sema.h:12410
void DiscardMisalignedMemberAddress(const Type *T, Expr *E)
This function checks if the expression is in the sef of potentially misaligned members and it is conv...
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:20571
ExprResult BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl=DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr=nullptr, SourceLocation opLoc=SourceLocation())
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
bool isConstantEvaluatedContext() const
Definition: Sema.h:1865
ASTContext & getASTContext() const
Definition: Sema.h:528
ExprResult BuiltinShuffleVector(CallExpr *TheCall)
BuiltinShuffleVector - Handle __builtin_shufflevector.
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9368
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
SourceManager & SourceMgr
Definition: Sema.h:862
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle.
DiagnosticsEngine & Diags
Definition: Sema.h:861
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:10673
FormatStringType
Definition: Sema.h:1896
@ FST_NSString
Definition: Sema.h:1899
@ FST_Printf
Definition: Sema.h:1898
@ FST_FreeBSDKPrintf
Definition: Sema.h:1903
@ FST_Scanf
Definition: Sema.h:1897
@ FST_OSLog
Definition: Sema.h:1905
@ FST_OSTrace
Definition: Sema.h:1904
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:547
ExprResult BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, SourceLocation RParenLoc, MultiExprArg Args, AtomicExpr::AtomicOp Op, AtomicArgumentOrder ArgOrder=AtomicArgumentOrder::API)
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:525
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition: Expr.h:4483
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
unsigned getPresumedLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
SourceLocation getTopMacroCallerLoc(SourceLocation Loc) const
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer.
unsigned getSpellingLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
child_range children()
Definition: Stmt.cpp:287
StmtClass getStmtClass() const
Definition: Stmt.h:1358
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1773
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:1954
bool isUTF8() const
Definition: Expr.h:1899
bool isWide() const
Definition: Expr.h:1898
bool isPascal() const
Definition: Expr.h:1903
unsigned getLength() const
Definition: Expr.h:1890
StringLiteralKind getKind() const
Definition: Expr.h:1893
SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, const TargetInfo &Target, unsigned *StartToken=nullptr, unsigned *StartTokenByteOffset=nullptr) const
getLocationOfByte - Return a source location that points to the specified byte of this string literal...
Definition: Expr.cpp:1384
bool isUTF32() const
Definition: Expr.h:1901
unsigned getByteLength() const
Definition: Expr.h:1889
StringRef getString() const
Definition: Expr.h:1850
bool isUTF16() const
Definition: Expr.h:1900
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.h:1955
bool isOrdinary() const
Definition: Expr.h:1897
unsigned getCharByteWidth() const
Definition: Expr.h:1891
bool isUnion() const
Definition: Decl.h:3792
Exposes information about the current target.
Definition: TargetInfo.h:213
virtual bool validatePointerAuthKey(const llvm::APSInt &value) const
Determine whether the given pointer-authentication key is valid.
Definition: TargetInfo.cpp:963
virtual bool supportsCpuSupports() const
Definition: TargetInfo.h:1477
virtual bool validateCpuIs(StringRef Name) const
Definition: TargetInfo.h:1497
virtual bool supportsCpuInit() const
Definition: TargetInfo.h:1479
IntType getInt64Type() const
Definition: TargetInfo.h:400
virtual bool useFP16ConversionIntrinsics() const
Check whether llvm intrinsics such as llvm.convert.to.fp16 should be used to convert to and from __fp...
Definition: TargetInfo.h:971
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
Definition: TargetInfo.cpp:270
IntType getSizeType() const
Definition: TargetInfo.h:366
const llvm::fltSemantics & getLongDoubleFormat() const
Definition: TargetInfo.h:764
IntType getIntPtrType() const
Definition: TargetInfo.h:392
uint32_t getARMCDECoprocMask() const
For ARM targets returns a mask defining which coprocessors are configured as Custom Datapath.
Definition: TargetInfo.h:1031
virtual bool validateCpuSupports(StringRef Name) const
Definition: TargetInfo.h:1483
virtual bool supportsCpuIs() const
Definition: TargetInfo.h:1478
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1235
virtual bool checkArithmeticFenceSupported() const
Controls if __arithmetic_fence is supported in the targeted backend.
Definition: TargetInfo.h:1636
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1451
virtual bool hasSjLjLowering() const
Controls if __builtin_longjmp / __builtin_setjmp can be lowered to llvm.eh.sjlj.longjmp / llvm....
Definition: TargetInfo.h:1685
A template argument list.
Definition: DeclTemplate.h:244
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:280
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
Definition: DeclTemplate.h:265
Represents a template argument.
Definition: TemplateBase.h:61
QualType getNonTypeTemplateArgumentType() const
If this is a non-type template argument, get its type.
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:319
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
Definition: TemplateBase.h:363
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:326
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
const Type * getTypeForDecl() const
Definition: Decl.h:3416
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:153
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition: Type.h:5074
A container of type source information.
Definition: Type.h:7130
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7141
The base class of the type hierarchy.
Definition: Type.h:1607
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1870
bool isBlockPointerType() const
Definition: Type.h:7420
bool isVoidType() const
Definition: Type.h:7723
bool isBooleanType() const
Definition: Type.h:7851
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2155
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:7898
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:729
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2134
bool isFloat16Type() const
Definition: Type.h:7732
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:2205
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2059
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:7878
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Definition: Type.cpp:2009
bool isVoidPointerType() const
Definition: Type.cpp:654
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition: Type.cpp:2340
bool isArrayType() const
Definition: Type.h:7478
bool isCharType() const
Definition: Type.cpp:2077
bool isFunctionPointerType() const
Definition: Type.h:7446
bool isPointerType() const
Definition: Type.h:7412
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7763
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8008
bool isReferenceType() const
Definition: Type.h:7424
bool isEnumeralType() const
Definition: Type.h:7510
bool isScalarType() const
Definition: Type.h:7822
bool isVariableArrayType() const
Definition: Type.h:7490
bool isClkEventT() const
Definition: Type.h:7625
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2487
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2046
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:694
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:7838
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition: Type.cpp:2224
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2513
bool isImageType() const
Definition: Type.h:7637
bool isPipeType() const
Definition: Type.h:7654
bool isLValueReferenceType() const
Definition: Type.h:7428
bool isBitIntType() const
Definition: Type.h:7658
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:7692
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:7502
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2449
bool isFloat32Type() const
Definition: Type.h:7736
bool isAnyComplexType() const
Definition: Type.h:7514
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7776
bool isHalfType() const
Definition: Type.h:7727
const BuiltinType * getAsPlaceholderType() const
Definition: Type.h:7705
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition: Type.cpp:2174
QualType getCanonicalTypeInternal() const
Definition: Type.h:2732
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2444
bool isQueueT() const
Definition: Type.h:7629
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:7891
bool isMemberPointerType() const
Definition: Type.h:7460
bool isAtomicType() const
Definition: Type.h:7557
bool isFunctionProtoType() const
Definition: Type.h:2284
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition: Type.cpp:2961
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2467
bool isObjCObjectType() const
Definition: Type.h:7548
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:7994
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:7857
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2195
bool isEventT() const
Definition: Type.h:7621
bool isBFloat16Type() const
Definition: Type.h:7744
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2350
bool isFunctionType() const
Definition: Type.h:7408
bool isObjCObjectPointerType() const
Definition: Type.h:7544
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition: Type.cpp:2246
bool isStructureOrClassType() const
Definition: Type.cpp:646
bool isVectorType() const
Definition: Type.h:7518
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2254
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2474
bool isFloatingType() const
Definition: Type.cpp:2237
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:2184
bool isAnyPointerType() const
Definition: Type.h:7416
TypeClass getTypeClass() const
Definition: Type.h:2094
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: Type.h:2120
bool isSamplerT() const
Definition: Type.h:7617
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7941
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:604
bool isNullPtrType() const
Definition: Type.h:7756
bool isRecordType() const
Definition: Type.h:7506
bool isObjCRetainableType() const
Definition: Type.cpp:4873
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4616
bool isUnionType() const
Definition: Type.cpp:660
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition: Type.cpp:2456
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1874
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3434
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition: Expr.h:2620
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2235
Opcode getOpcode() const
Definition: Expr.h:2275
Expr * getSubExpr() const
Definition: Expr.h:2280
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:2357
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
A set of unresolved declarations.
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3317
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:707
QualType getType() const
Definition: Decl.h:718
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition: Decl.cpp:5370
Represents a variable declaration or definition.
Definition: Decl.h:919
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2191
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2555
Represents a GCC generic vector type.
Definition: Type.h:3769
unsigned getNumElements() const
Definition: Type.h:3784
WhileStmt - This represents a 'while' stmt.
Definition: Stmt.h:2584
MatchKind
How well a given conversion specifier matches its argument.
Definition: FormatString.h:271
@ NoMatch
The conversion specifier and the argument types are incompatible.
Definition: FormatString.h:274
@ NoMatchPedantic
The conversion specifier and the argument type are disallowed by the C standard, but are in practice ...
Definition: FormatString.h:286
@ Match
The conversion specifier and the argument type are compatible.
Definition: FormatString.h:277
@ NoMatchSignedness
The conversion specifier and the argument type have different sign.
Definition: FormatString.h:288
std::string getRepresentativeTypeName(ASTContext &C) const
MatchKind matchesType(ASTContext &C, QualType argTy) const
std::optional< ConversionSpecifier > getStandardSpecifier() const
ArgType getArgType(ASTContext &Ctx) const
Defines the clang::TargetInfo interface.
__inline void unsigned int _2
Definition: larchintrin.h:181
bool evaluateRequiredTargetFeatures(llvm::StringRef RequiredFatures, const llvm::StringMap< bool > &TargetFetureMap)
Returns true if the required target features of a builtin function are enabled.
bool parseFormatStringHasFormattingSpecifiers(const char *Begin, const char *End, const LangOptions &LO, const TargetInfo &Target)
Return true if the given string has at least one formatting specifier.
bool ParsePrintfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target, bool isFreeBSDKPrintf)
bool ParseScanfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
bool ParseFormatStringHasSArg(const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
const AstTypeMatcher< PointerType > pointerType
Matches pointer types, but does not match Objective-C object pointer types.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
ComparisonResult
Indicates the result of a tentative comparison.
uint32_t Literal
Literals are represented as positive integers.
static constexpr Variable var(Literal L)
Returns the variable of L.
uint32_t Variable
Boolean variables are represented as positive integers.
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Definition: DiagnosticIDs.h:65
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
Definition: Types.cpp:218
@ After
Like System, but searched after the system directories.
@ FixIt
Parse and apply any fixits to the source.
llvm::APFloat APFloat
Definition: Floating.h:23
bool GT(InterpState &S, CodePtr OpPC)
Definition: Interp.h:890
llvm::APInt APInt
Definition: Integral.h:29
bool Call(InterpState &S, CodePtr OpPC, const Function *Func, uint32_t VarArgSize)
Definition: Interp.h:2148
bool NE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:868
bool LE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:882
bool InRange(InterpState &S, CodePtr OpPC)
Definition: Interp.h:909
bool Load(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1385
bool Cast(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1707
bool EQ(InterpState &S, CodePtr OpPC)
Definition: Interp.h:837
bool GE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:897
std::string toString(const til::SExpr *E)
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition: FixIt.h:32
RangeSelector member(std::string ID)
Given a MemberExpr, selects the member token.
std::shared_ptr< MatchComputation< T > > Generator
Definition: RewriteRule.h:65
The JSON file list parser is used to communicate input to InstallAPI.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
ObjCStringFormatFamily
@ CPlusPlus
Definition: LangStandard.h:55
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ NonNull
Values of this type can never be null.
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition: Specifiers.h:146
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:148
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition: Specifiers.h:151
Expr * IgnoreImplicitAsWrittenSingleStep(Expr *E)
Definition: IgnoreExpr.h:137
BinaryOperatorKind
@ SC_Register
Definition: Specifiers.h:254
Expr * IgnoreElidableImplicitConstructorSingleStep(Expr *E)
Definition: IgnoreExpr.h:125
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
LLVM_READONLY bool isLowercase(unsigned char c)
Return true if this character is a lowercase ASCII letter: [a-z].
Definition: CharInfo.h:121
ExprResult ExprError()
Definition: Ownership.h:264
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
Expr * IgnoreExprNodes(Expr *E, FnTys &&... Fns)
Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *, Recursively apply each of the f...
Definition: IgnoreExpr.h:34
CastKind
CastKind - The kind of operation required for a conversion.
ActionResult< ParsedType > TypeResult
Definition: Ownership.h:250
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:129
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
for(const auto &A :T->param_types())
const FunctionProtoType * T
StringLiteralKind
Definition: Expr.h:1744
raw_ostream & Indent(raw_ostream &Out, const unsigned int Space, bool IsDot)
Definition: JsonSupport.h:21
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
@ CC_Win64
Definition: Specifiers.h:282
@ CC_C
Definition: Specifiers.h:276
@ CC_X86_64SysV
Definition: Specifiers.h:283
@ AltiVecVector
is AltiVec vector
@ Generic
not a target-specific vector type
U cast(CodeGen::Address addr)
Definition: Address.h:291
@ Other
Other implicit parameter.
@ AS_public
Definition: Specifiers.h:121
unsigned long uint64_t
long int64_t
Definition: Format.h:5394
float __ovld __cnfn distance(float, float)
Returns the distance between p0 and p1.
#define true
Definition: stdbool.h:21
#define false
Definition: stdbool.h:22
#define bool
Definition: stdbool.h:20
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:644
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition: Expr.h:630
Extra information about a function prototype.
Definition: Type.h:4535
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
unsigned AnonymousTagLocations
When printing an anonymous tag name, also print the location of that entity (e.g.,...
unsigned Indentation
The number of spaces to use to indent each line.
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:9997
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition: Sema.h:10114
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition: Sema.h:10140
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition: Sema.h:10130
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition: Sema.h:10095
FormatArgumentPassingKind ArgPassingKind
Definition: Sema.h:1884
#define log2(__x)
Definition: tgmath.h:970